<?
require_once('version.inc');
require_once('dbaccess.inc');
require_once('language.inc');
require_once('header.inc');
require_once('helper.inc');
require_once('crypt.inc');
require_once('settings.inc');

$drm = array(true, false, false, false, true, true, true);

$knopf = 0;
$func = $_REQUEST['func'];
$editplan = $_REQUEST['editplan'];
$viewplan = $_REQUEST['viewplan'];
$deleteplan = $_REQUEST['deleteplan'];
$editcopy = $_REQUEST['editcopy'];
$taskadd = $_REQUEST['taskadd'];
$deletetask = $_REQUEST['deletetask'];
$edittask = $_REQUEST['edittask'];
$addmi = $_REQUEST['addmi'];
$addmidel = $_REQUEST['addmidel'];
$addmiadd = $_REQUEST['addmiadd'];
$moveup = $_REQUEST['moveup'];
$movedown = $_REQUEST['movedown'];

if (isset($editplan)) {
   $headline = 20;
   $pl_num = $editplan;
} else {
   $pl_num = 0;
}

if (isset($deleteplan)) {
   $headline = 21;
}

if (isset($_REQUEST['no'])) {
   $headline = 9;
}

# Planungsmenue
//if (isset($_REQUEST['plan'])) { $knopf = 2; $headline = 9; $menu = 2; }
if (isset($_REQUEST['plan'])) { $knopf = 2; $headline = 20; $menu = 2; }

if (isset($_REQUEST['plneu'])) { $knopf = 10; $headline = 19; }
if (isset($_REQUEST['plchange'])) { $knopf = 11; $headline = 20; }
if (isset($_REQUEST['plumplan'])) { $knopf = 12; }

require_once('menu.inc');
require_once('knumber.inc');
require_once('class_tasknum.inc');

$ab_datum = 0;

# Folgende Funktion zeigt in einer Tabelle die Planstammdaten an, welche
# mit Hilfe der Buttons in der ersten Spalte bearbeitet werden koennen.
#
# Es handelt sich dabei um die Liste der Plaene, die zur Betrachtung oder
# auch zur Bearbeitung stehen. Der Projektleiter sieht alle Plaene, bei
# denen er Projektleiter ist und der Administrator sieht immer alle
# Plaene.
#
function ShowPlan($rstufe, $menu, $unum, $plnum=0) {
	global $rstufe;
	global $unum;
	global $phase;
	global $pmlight;
	global $statusbericht;
	global $menu;
	global $headline;
	global $func;
	global $pj_lock;
	global $dtformatshort;

	# Als erstes wird eine Auswahlbox angezeigt, in der der User die
	# Anzeige ein wenig individualisieren kann.
	$ps_1 = $_REQUEST['ps_1'];
	$ps_2 = $_REQUEST['ps_2'];
	$ps_3 = $_REQUEST['ps_3'];
	$ps_4 = $_REQUEST['ps_4'];
	$ps_5 = $_REQUEST['ps_5'];
	$ps_6 = $_REQUEST['ps_6'];
	$sx_prnum = $_REQUEST['sx_prnum'];
	$sx_prname = $_REQUEST['sx_prname'];

	if ($func != "SHOWPLAN") {
	   $ps_1 = 1;
	   $ps_2 = 1;
	   $ps_4 = 1;
	}

	$db = OpenDB();
?>
<form name="stati" method="post" action="plan.php" onChange="javascript:this.submit()">
<input type="hidden" name="menu" value="<? echo "$menu"; ?>">
<input type="hidden" name="headline" value="<? echo "$headline"; ?>">
<input type="hidden" name="plchange" value="1">
<input type="hidden" name="func" value="SHOWPLAN">
<table class="input">
   <tr>
      <th class="sel" colspan=2><? Output($db, 23, "Pl&auml;ne mit folgendem Status anzeigen"); ?></th>
      <th class="sel" colspan=2><? Output($db, 24, "Projektsuche"); ?></th>
   </tr>
   <tr>
      <td><? Output($db, 25, "In Erstellung:"); ?></td>
      <td><input type="checkbox" name="ps_1" value="1" <? if ($ps_1) echo "checked"; ?>></td>
      <td class="input_l">Projektnummer:</td>
      <td><input type="text" name="sx_prnum" value="<? echo "$sx_prnum"; ?>" size=8 maxlength=16></td>
   </tr>
<?
	if (!$pmlight) {
?>
   <tr>
      <td><? Output($db, 26, "Freigegeben:"); ?></td>
      <td><input type="checkbox" name="ps_2" value="1" <? if ($ps_2) echo "checked"; ?>></td>
      <td rowspan=4 class="input_l">Projektname:</td>
      <td rowspan=4 valign="top"><input type="text" name="sx_prname" value="<? echo "$sx_prname"; ?>" size=20 mxlength=100></td>
   </tr>
<?
	}
?>
   <tr>
      <td><? Output($db, 27, "Aktiv:"); ?></td>
      <td><input type="checkbox" name="ps_4" value="1" <? if ($ps_4) echo "checked"; ?>></td>
<?
	if ($pmlight) {
?>
      <td rowspan=3 class="input_l"><? Output($db, 28, "Projektname:"); ?></td>
      <td rowspan=3 valign="top"><input type="text" name="sx_prname" value="<? echo "$sx_prname"; ?>" size=20 mxlength=100></td>
<?
	}
?>
   </tr>
   <tr>
      <td><? Output($db, 29, "Inaktiv:"); ?></td>
      <td><input type="checkbox" name="ps_5" value="1" <? if ($ps_5) echo "checked"; ?>></td>
   </tr>
   <tr>
      <td><? Output($db, 30, "Abgeschlossen:"); ?></td>
      <td><input type="checkbox" name="ps_6" value="1" <? if ($ps_6) echo "checked"; ?>></td>
   </tr>
   <tr>
      <td class="sel" colspan = 4><center>
<?
	Button(GetMessage($db, 31, "Selektion durchf&uuml;hren"), "stati");
?>
      </center></td>
   </tr>
</table>
</form>
<?
	if (!isset($ps_1) && !isset($ps_2) && !isset($ps_3) && !isset($ps_4) && !isset($ps_5) && !isset($ps_6)) {
	   echo "<p class=\"cry\">" . Output($db, 32, "Es wurden keine Pl&auml;ne gefunden!") . "</p>\n";
	   return;
	}

	$old_prnum = 0;
	$db = OpenDB();
	$dtdb = GetDBDateFormat(true);
	$query = "select pl_num, pl_lfd, pl_prnum, pl_status, pr_name, ";
	$query .= "pr_status, to_char(pl_date, '$dtdb'), pl_comment ";
	$query .= "from plan, project where pr_num = pl_prnum ";

	if ($rstufe == 2)
	   $query .= "and pr_pl = $unum ";

	if (isset($sx_prnum) && strlen($sx_prnum) > 0)
	   $query .= "and pr_num = $sx_prnum ";
	else if (isset($sx_prname) && strlen($sx_prname) > 0)
	   $query .= "and pr_name ilike '$sx_prname%' ";

	$query .= "and pr_status = 0 and pl_status in (";
	$komma = false;

	if ($ps_1) {
	   $query .= "1";
	   $komma = true;
	}

	if ($ps_2) {
	   if ($komma)
	      $query .= ",";

	   $query .= "2";
	   $komma = true;
	}

	if ($ps_3) {
	   if ($komma)
	      $query .= ",";

	   $query .= "3";
	   $komma = true;
	}

	if ($ps_4) {
	   if ($komma)
	      $query .= ",";

	   $query .= "4";
	   $komma = true;
	}

	if ($ps_5) {
	   if ($komma)
	      $query .= ",";

	   $query .= "5";
	   $komma = true;
	}

	if ($ps_6) {
	   if ($komma)
	      $query .= ",";

	   $query .= "6";
	   $komma = true;
	}

	$query .= ") ";
	$query .= "order by pl_prnum asc, pl_lfd desc";
	$result = QueryDB($db, $query);

	if (!$result) {
	   include('footer.inc');
	   return;
	}

	$numrows = numrowsDB($result);
	$nav = "menu=$menu&headline=9&ps_1=$ps_1&ps_2=$ps_2&ps_3=$ps_3&ps_4=$ps_4&ps_5=$ps_5&ps_6=$ps_6";

	if ($numrows > 0) {
	   echo "<form name=\"plan\" action=\"plan.php\" method=\"post\">\n";
	   echo "<input type=\"hidden\" name=\"pl_num\" value=\"$plnum\">\n";
	   echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
	   echo "<input type=\"hidden\" name=\"headline\" value=\"9\">\n";
	   echo "<input type=\"hidden\" name=\"ps_1\" value=\"$ps_1\">\n";
	   echo "<input type=\"hidden\" name=\"ps_2\" value=\"$ps_2\">\n";
	   echo "<input type=\"hidden\" name=\"ps_3\" value=\"$ps_3\">\n";
	   echo "<input type=\"hidden\" name=\"ps_4\" value=\"$ps_4\">\n";
	   echo "<input type=\"hidden\" name=\"ps_5\" value=\"$ps_5\">\n";
	   echo "<input type=\"hidden\" name=\"ps_6\" value=\"$ps_6\">\n";

	   if ($plnum > 0) {
	      echo "<input type=\"hidden\" name=\"func\" value=\"UpdatePlan\">\n";
	   }
?>
<table class="sel">
   <tr>
      <th class="sel"><? Output($db, 33, "Aktion"); ?></th>
      <th class="sel"><? Output($db, 34, "Lfd.Nr."); ?></th>
      <th class="sel"><? Output($db, 35, "Proj.Nr."); ?></th>
      <th class="sel"><? Output($db, 36, "Projektbezeichnung"); ?></th>
      <th class="sel"><? Output($db, 37, "Planstatus"); ?></th>
      <th class="sel"><? Output($db, 403, "Abg. bis"); ?></th>
<?
	if ($statusbericht) {
	   echo "      <th class=\"sel\">" . GetMessage($db, 38, "Statusbericht") . "</th>";
	} else {
	   echo "      <th class=\"sel\">" . GetMessage($db, 39, "Beschreibung") . "</th>";
	}
?>
   </tr>
<?php
	   $old_plnum = 0;
	   $oo_prnum = 0;
	   $row = 0;
	   $inp_com = false;

	   while ($row < $numrows) {
	      $data = fetchDB($result, $row);
	      $pl_num = $data[0];
	      $pl_lfd = $data[1];
	      $pl_prnum = $data[2];
	      $pl_status = $data[3];
	      $pr_name = $data[4];
	      $ks_status = $data[5];
	      $pl_date = $data[6];
	      $pl_comment = $data[7];

	      if ($oo_prnum != $pl_prnum)
	         $old_pllfd = $pl_lfd;

	      # Pruefen, ob bereits IST-Buchungen vorgenommen wurden. Wenn ja,
	      # dann darf der Plan nicht mehr geloescht werden koennen!
	      #
	      $query = "select wd_num from wdone, task where ";
	      $query .= "wd_prnum = $pl_prnum and ta_num = wd_task and ";
	      $query .= "ta_plnum = $pl_num";

	      if (!($resta = QueryDB($db, $query)))
	         return;

	      if (numrowsDB($resta) <= 0)
	         $del = true;
	      else
	         $del = false;

	      echo "<tr><td class=\"selakt\"><table border=0 cellspacing=0 cellpadding=0><tr>";

	      if ($pl_status < 3 && $old_prnum != $pl_prnum) {
	         echo "<td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php','editplan=$pl_num&$nav')\"><img src=\"image/edit.png\" border=0 alt=\"Edit\"></a></td>";
		 $old_prnum = $pl_prnum;
		 $inp_com = true;
	      } else {
	         echo "<td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php','viewplan=$pl_num&$nav')\"><img src=\"image/view.png\" width=15 height=15 border=0 alt=\"View\"></a></td>";
	      }

	      if ($del && $pl_status < 4 && ($rstufe == 1 || $rstufe == 2))
	         echo "<td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php','deleteplan=$pl_num&$nav')\"><img src=\"image/editdelete.png\" border=0 alt=\"Delete\"></a></td>";

	      if ($pl_status > 1 && $pl_status < 5) {
		 echo "<td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php','editcopy=$pl_num&pl_prnum=$pl_prnum&pl_status=1&$nav')\"><img src=\"image/editcopy.png\" border=0 alt=\"Copy\"></a></td>";

		 if (!$pj_lock)
		    echo "<td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php','func=LockM&pl_num=$pl_num&pl_prnum=$pl_prnum&pl_status=$pl_status&$nav')\"><img src=\"image/month.png\" border=0 alt=\"Copy\"></a></td>";
	      }

	      echo "</tr></table>";
	      echo "</td>\n<td class=\"selnum\">$pl_lfd</td>\n<td class=\"selnum\">$pl_prnum</td>\n";

	      if ($inp_com) {
	         echo "<td class=\"sel\">";
		 echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','editplan=$pl_num&$nav')\">";
		 echo "$pr_name</a></td>\n";
		 $inp_com = false;
	      } else
	         echo "<td class=\"sel\">$pr_name</td>\n";

	      if ($plnum == $pl_num) {
	         echo "<td sel=\"sel\"><select name=\"pl_status\">\n";
		 $status = $_REQUEST['pl_status'];

		 if ($status == 3)
		    $j = 4;
		 else
		    $j = 1;

		 for ($i = $j; $i <= 6; $i++) {
		    if (($i == 2 && $pmlight) || $i == 3 || $i == 5)
		       continue;

		    if ($rstufe == 2 && $status == 6 && $i == 1)
		       continue;

		    if ($status == $i)
		       echo "<option value=\"$i\" selected>";
		    else
		       echo "<option value=\"$i\">";

	            switch ($i) {
	               case 1: Output($db, 40, "In Erstellung (&auml;nderbar, nicht bebuchbar)"); break;
		       case 2: Output($db, 41, "Freigegeben (&auml;nderbar, bebuchbar)"); break;
//		       case 3: echo "Wartet auf Genehmigung"; break;
		       case 4: Output($db, 42, "Aktiv (nicht &auml;nderbar, bebuchbar)"); break;
		       case 5: Output($db, 43, "Inaktiv (nicht &auml;nderbar, nicht bebuchbar)"); break;
		       case 6: Output($db, 44, "Abgeschlossen (Projekt ist abgeschlossen)"); break;
//		       default: echo "In Erstellung";
	            }

		    echo "</option>\n";
		 }

		 echo "</select>";
		 Button(GetMessage($db, 45, "Speichern"), "plan");
		 echo "</td>\n";
	      } else if ($oo_prnum != $pl_prnum && $old_pllfd >= $pl_lfd) {
	         echo "<td class=\"sel\">";

//		 if ($pl_status < 4 || $rstufe == 1 || $rstufe == 4) {
		    echo "<a href=\"#\" onClick=";
	            echo "\"javascript:MoveTo('plan.php','pl_num=$pl_num&pl_status=$pl_status&func=EditPlStatus&$nav')\">\n";
//		 }

	         switch ($pl_status) {
	            case 1: Output($db, 85, "In Erstellung"); break;
		    case 2: Output($db, 86, "Freigegeben"); break;
		    case 3: echo "Wartet auf Genehmigung"; break;
		    case 4: Output($db, 87, "Aktiv"); break;
		    case 5: Output($db, 88, "Inaktiv"); break;
		    case 6: Output($db, 89, "Abgeschlossen"); break;
		    default: Output($db, 85, "In Erstellung");
	         }

//	         if ($pl_status < 4)
		    echo "</a>";

		 echo "</td>";
		 $oo_prnum = $pl_prnum;
		 $inp_com = true;
	      } else {
	         echo "<td class=\"sel\">\n";

	         switch ($pl_status) {
	            case 1: Output($db, 85, "In Erstellung"); break;
		    case 2: Output($db, 86, "Freigegeben"); break;
		    case 3: echo "Wartet auf Genehmigung"; break;
		    case 4: Output($db, 87, "Aktiv"); break;
		    case 5: Output($db, 88, "Inaktiv"); break;
		    case 6: Output($db, 89, "Abgeschlossen"); break;
		    default: Output($db, 85, "In Erstellung");
	         }

	         echo "</td>\n";
	      }

	      # Letzter Teilprojektabschluss
	      $query = "select ab_datum from abschluss where ";
	      $query .= "ab_prnum = $pl_prnum order by ab_datum desc";

	      if (!($resab = QueryDB($db, $query))) {
	         closeDB($db);
		 return;
	      }

	      if (numrowsDB($resab) > 0) {
	         $data = fetchDB($resab, 0);
		 $ab_datum = $data[0];
		 $dt = gmdate($dtformatshort, $ab_datum);
	      } else
	         $dt = "";

	      echo "<td class=\"selnum\">$dt</td>\n";

	      # Kommentar / Beschreibung / Statusbericht
	      if ($statusbericht) {
	         $query = "select ps_prstat from planstatus where ";
	         $query .= "ps_prnum = $pl_prnum  and ps_status = true and ";
	         $query .= "ps_plnum = $pl_num ";
		 $query .= "order by ps_lfd desc";

	         if (!($resps = QueryDB($db, $query))) {
	            closeDB($db);
		    return;
	         }

		 $anzps = numrowsDB($resps);

		 if ($anzps > 0) {
		    $data = fetchDB($resps, 0);
	            $ps_prstat = $data[0];
		 } else
		    $ps_prstat = 3;

	         echo "<td class=\"sel\">$pl_date&nbsp;&nbsp;<img src=\"";

		 switch ($ps_prstat) {
		    case 0: echo "image/cool.gif\" alt=\"Gruen"; break;
		    case 1: echo "image/shocked.gif\" alt=\"Gelb"; break;
		    case 2: echo "image/sad.gif\" alt=\"Rot"; break;
		    default: echo "image/huh.gif\" alt=\"Undefiniert";
		 }

		 echo "\" width=17 height=17>";

	         if ($inp_com && $pl_status > 1 && $pl_status < 5) {
		    echo "&nbsp;&nbsp;<a href=\"#\" ";
		    echo "onClick=\"javascript:MoveTo('plan.php','func=PLANSTATUS&pr_num=$pl_prnum&pl_num=$pl_num&$nav')\">";
		    echo "<img src=\"image/edit.png\" border=0 alt=\"Statusbericht\"></a>";
		 } else if ($pl_status > 4) {
		    echo "&nbsp;&nbsp;<a href=\"#\" ";
		    echo "onClick=\"javascript:MoveTo('plan.php','func=PLANSTATUS&lock=1&pr_num=$pl_prnum&pl_num=$pl_num&$nav')\">";
		    echo "<img src=\"image/view.png\" border=0 alt=\"Statusbericht ansehen\" width=15 height=15></a>";
		 }

		 echo "</td>\n";
		 $inp_com = false;
	      } else {
	         echo "<td class=\"sel\"><table border=0 cellspacing=0 cellpadding=0><tr><td>$pl_date&nbsp;&nbsp;</td><td>";
		 $inp_com = false;
		 echo substr($pl_comment, 0, 30);
		 echo "</td></tr></table></td>\n";
	      }

	      echo "</tr>\n";
	      $row++;
	   }

	   echo "</table>\n";

	   if ($plnum > 0)
	      echo "</form>\n";
	} else {
	   echo "<p class=\"cry\">" . GetMessage($db, 32, "Es wurden keine Pl&auml;ne gefunden!") . "</p>\n";
	}

	closeDB($db);
}

function AskClosePlan($anz) {
	$headline = $_REQUEST['headline'];
	$menu = $_REQUEST['menu'];
	$pl_num = $_REQUEST['pl_num'];
	$pl_status = $_REQUEST['pl_status'];
	$nav = "pl_num=$pl_num&pl_status=$pl_status&menu=$menu&func=WriteStatus&headline=21";
?>
<br>
<form action="plan.php" method="post">
<table border=2 class="alarm">
   <tr><td colspan=2><big><? Output(-1, 46, "Warnung!"); ?></big><br><br>
<?	Output(-1, 47, "
           Es existieren noch %d Tasks, die noch nicht zu Ende sind.<br>
           Wenn Sie diesen Plan nun abschliessen, k&ouml;nnen Sie keine
           IST-Buchungen mehr auf dieses Projekt vornehmen. Sobald ein Plan
           abgeschlossen ist, ist das gesamte Projekt abgeschlossen!
	   <br><br>
	   Wollen Sie wirklich dieses Projekt abschliessen?", $anz);
?>
      </td>
   </tr>
   <tr>
      <td><center><input type="button" name="yes" value="<? Output(-1, 48, "Projekt Abschliessen"); ?>" onClick="javascript:MoveTo('plan.php','yes=yes&<? echo "$nav"; ?>')"></center></td>
      <td><center><input type="button" name="no" value="<? Output(-1, 49, "Abbruch"); ?>" onClick="javascript:MoveTo('plan.php','no=no&<? echo "$nav"; ?>')"></center></td>
   </tr>
</table>
</form>
<?php
}

# Folgende Funktion schreibt den (eventuell) geaenderten Status eines Plans
# in die Datenbank.
#
function UpdatePlan($write=false) {
	global $rstufe;
	global $phase;
	global $pmlight;
	global $language;
	global $unum;

	if ($rstufe != 1 && $rstufe != 2) {
	   Error(GetMessage(-1, 50, "Berechtigungsfehler!"));
	   return false;
	}

	$pl_num = $_REQUEST['pl_num'];
	$pl_status = $_REQUEST['pl_status'];

	if (!isset($pl_num) || $pl_num <= 0) {
	   Error(GetMessage(-1, 341, "Interner Fehler: Plannummer fehlt!"));
	   return false;
	}

	if (!isset($pl_status) || $pl_status < 1 || $pl_status > 6) {
	   Error(GetMessage(-1, 379, "Interner Fehler: Fehlender oder ung&uuml;ltiger Status!"));
	   return false;
	}

	$db = OpenDB();

	# Bevor wir den Planstatus von 6 tatsaechlich schreiben pruefen wir, ob
	# nicht noch ein Task des Plans offen ist. Ist dem so, warnen wir den
	# User und weisen ihn auf die Konsequenzen hin.
	if (!$write && $pl_status == 6) {
	   $today = time();
	   $query = "select count(*) from task where ";
	   $query .= "ta_plnum = $pl_num and ta_start+(ta_duration*86400) > $today and ";
	   $query .= "ta_level > 1";

	   if (!($result = QueryDB($db, $query)))
	      return false;

	   $data = fetchDB($result, 0);
	   $anz = $data[0];

	   if ($anz > 0) {
	      AskClosePlan($anz);
	      return true;
	   }
	}

	# Handelt es sich um den Planstatus 1 pruefen wir, ob der Plan
	# zuvor nicht bereits einen anderen Status hatte und wenn ja, ob
	# IST-Buchungen vorgenommen wurden. Trifft das zu, darf der Status
	# nicht auf 1 gesetzt werden.
	if ($pl_status == 1) {
	   $query = "select count(*) from wdone, task where ";
	   $query .= "ta_plnum = $pl_num and wd_task = ta_num";

	   if (!($result = QueryDB($db, $query)))
	      return false;

	   $data = fetchDB($result, 0);
	   $anz = $data[0];

	   if ($anz > 0) {
	      Error(GetMessage($db, 380, "Auf diesem Plan sind bereits IST-Buchungen vorhanden! Der Planstatus kann daher nicht auf \"In Erstellung\" zur&uuml;ck gesetzt werden!"));
	      return false;
	   }
	}

	# In der strikten Periodensicht ($pmlight == true), darf der Status nur
	# dann auf > 1 gesetzt werden, wenn es einen Kommentar zum Plan gibt.
	# Falls es also keinen Kommentar gibt, wird dieser automatisch erzeugt.
	#
	if ($pmlight && $pl_status > 1) {
	   $query = "select pl_comment from plan where pl_num = $pl_num";

	   if (!($result = QueryDB($db, $query)))
	      return false;

	   $data = fetchDB($result, 0);
	   $pl_comment = $data[0];

	   if (!isset($pl_comment) || strlen($pl_comment) <= 0) {
	      $query = "select mi_nname, mi_vname from mitarbeiter where mi_num = $unum";

	      if (!($resmi = QueryDB($db, $query)))
	         return false;

	      $data = fetchDB($resmi, 0);
	      $mi_nname = $data[0];
	      $mi_vname = $data[0];

	      $query = "update plan set pl_comment = '";
	      $query .= GetMessageLang($db, $language, 381, "Status�nderung durch %s", "$mi_nname $mi_vname");
	      $query .= "' where pl_num = $pl_num";

	      if (!QueryDB($db, $query))
	         return false;

	      Error(GetMessage($db, 382, "Der fehlende Kommentar zum Plan wurde automatisch eingef&uuml;gt!"));
	   }
	}

	$query = "update plan set pl_status = $pl_status ";

	if ($pl_status == 4)
	   $query .= ", pl_date = current_timestamp ";

	$query .= "where pl_num = $pl_num";

	if (!TQueryDB($db, $query)) {
	   closeDB($db);
	   return false;
	}

	# Handelt es sich nicht um den ersten Plan eines Projekts,
	# muessen alle aelteren Instanzen auf Inaktiv gesetzt werden.
	# Ausgenommen sind Plaene die Abgeschlossen sind (Status = 6).
	# Status 1 darf nur dann gesetzt werden koennen, wenn der
	# Plan noch keine IST-Buchungen hat. Ein neuerliches setzen
	# von Status 1 bewirkt, dass der folgende Plan auf 4 gesetzt
	# wird.
	$query = "select pl_prnum from plan where pl_num = $pl_num";

	if (!($result = QueryDB($db, $query)))
	   return false;

	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];

	$query = "select pl_num, pl_status from plan where ";
	$query .= "pl_prnum = $pl_prnum and pl_num != $pl_num ";
	$query .= "order by pl_lfd desc";
//	$query .= "and pl_status != 6 order by pl_lfd desc";

	if (!($result = QueryDB($db, $query)))
	   return false;

	$numrows = numrowsDB($result);
	$status = ($pl_status == 6) ? 6 : 5;

	if ($numrows > 0) {
	   QueryDB($db, "begin");
	   $j = 0;

	   while ($j < $numrows) {
	      $data = fetchDB($result, $j);
	      $pl_num = $data[0];
	      $pst = $data[1];

	      if ($j == 0 && $status != 6 && $pl_status == 1)
	         $query = "update plan set pl_status = 4, pl_date = current_timestamp ";
	      else
	         $query = "update plan set pl_status = $status ";

	      $query .= "where pl_num = $pl_num";

	      if ($pst != $status || ($j == 0 && $status != 6 && $pl_status == 1)) {
	         if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
		    closeDB($db);
		    return false;
	         }
	      }

	      $j++;
	   }

	   QueryDB($db, "commit");
	}

	closeDB($db);
	return true;
}

# Folgende Funktion speichert die zuvor erfassten Planstammdaten. Da die
# Erfassung ohnehin nur mittels ComboBox (select) moeglich ist, kann eine
# Plausibilitaetspruefung entfallen.
#
function SaveNewPlan() {
	global $phase;
	global $unum;

	$pl_prnum = $_REQUEST['pl_prnum'];
	$pl_status = $_REQUEST['pl_status'];
	$te_num = $_REQUEST['te_num'];

	$db = OpenDB();
	#
	# Zunaechst muessen wir die laufende Nummer (pl_lfd) ermitteln...
	#
	$query = "select pl_lfd, pl_status, pl_num from plan where ";
	$query .= "pl_prnum = $pl_prnum order by pl_lfd desc";

	if (!($respl = QueryDB($db, $query))) {
	   closeDB($db);
	   return 0;
	}

	$numrows = numrowsDB($respl);

	if ($numrows > 0) {
	   $data = fetchDB($respl, 0);
	   $pl_lfd = $data[0] + 1;
	} else {
	   $pl_lfd = 1;
	}

	$query = "select co_plan from counter";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$pl_num = $data[0] + 1;

	QueryDB($db, "begin");
	$query = "insert into plan (pl_num, pl_lfd, pl_prnum, pl_status) ";
	$query .= "values ($pl_num, $pl_lfd, $pl_prnum, $pl_status)";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return 0;
	}

	$query = "update counter set co_plan = $pl_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return 0;
	}

	# Handelt es sich nicht um den ersten Plan eines Projekts,
	# muessen alle aelteren Instanzen auf Inaktiv gesetzt werden.
	# Ausgenommen sind Plaene die Abgeschlossen sind (Status = 6)
	if ($numrows > 0 && $pl_status > 1) {
	   $j = 0;

	   while ($j < $numrows) {
	      $data = fetchDB($respl, $j);
	      $plstatus = $data[1];
	      $plnum = $data[2];

	      if ($plstatus != 6) {
		 $query = "update plan set pl_status = 5, pl_date = current_timestamp ";
		 $query .= "where pl_num = $plnum";

		 if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
		    closeDB($db);
		    return 0;
		 }
	      }

	      $j++;
	   }
	}

	QueryDB($db, "commit");

	# Wenn ein Template ausgewaehlt wurde, muss es ausgelesen werden
	# und als Plan angelegt werden.
	if (isset($te_num) && $te_num > 0) {
	   $query = "select co_task from counter";
	   $result = QueryDB($db, $query);

	   if (!$result) {
	      closeDB($db);
	      return 0;
	   }

	   $data = fetchDB($result, 0);
	   $co_task = $data[0];

	   $query = "select pt_lfd, pt_level, pt_name, pt_color, pt_meeting, ";
	   $query .= "pt_phase from ptemp where pt_tnum = $te_num ";
	   $query .= "order by pt_lfd";
	   $result = QueryDB($db, $query);

	   if (!$result) {
	      closeDB($db);
	      return 0;
	   }

	   $numrows = numrowsDB($result);
	   $row = 0;
	   QueryDB($db, "begin");

	   while ($row < $numrows) {
	      $data = fetchDB($result, $row);
	      $pt_lfd = $data[0];
	      $pt_level = $data[1];
	      $pt_name = addslashes($data[2]);
	      $pt_color = $data[3];
	      $pt_meeting = $data[4];
	      $pt_phase = $data[5];

	      if ($pt_meeting == "t")
	         $pt_meeting = 1;
	      else
	          $pt_meeting = 0;

	      $ta_start = time();
	      $co_task++;
	      $ta_hash = md5($co_task);
	      $query = "insert into task (ta_num, ta_plnum, ta_id, ta_name, ";
	      $query .= "ta_color, ta_shape, ta_meeting, ta_start, ";
	      $query .= "ta_duration, ta_complete, ta_priority, ta_level, ";
	      $query .= "ta_phase, ta_hash) values ($co_task, $pl_num, $pt_lfd, ";
	      $query .= "'$pt_name', $pt_color, '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0',";
	      $query .= "$pt_meeting, $ta_start, 1, 0, 1, $pt_level, $pt_phase, '$ta_hash')";

	      if (!QueryDB($db, $query)) {
		 QueryDB($db, "rollback");
		 closeDB($db);
		 return 0;
	      }

	      $row++;
	   }

	   $query = "update counter set co_task = $co_task";

	   if (!QueryDB($db, $query)) {
	      QueryDB($db, "rollback");
	      closeDB($db);
	      return 0;
	   }

	   QueryDB($db, "commit");
	}

	Journal(300, "plan.php: SaveNewPlan: plan=$pl_num", $db);
	closeDB($db);
	return $pl_num;
}

# Folgende Funktion zeigt die Erfassungsmaske fuer einen Task an. Es muss
# die interne Datensatznummer des Plans uebergeben werden auf die sich der
# Task bezieht und die ID, also die laufende Nummer. Diese laufende Nummer
# stellt sicher, das die Tasks immer in der richtigen Reihenfolge angezeigt
# werden.
#
function AddTask($ta_plnum, $ta_id) {
	$menu = $_REQUEST['menu'];
	global $unum;
	global $rstufe;
	global $phase;
	global $VisualDate;
	global $pmlight;
	global $verrmodul;

	if (!isset($ta_plnum) || $ta_plnum <= 0) {
	   Error(GetMessage(-1, 22, "Error: Interner Fehler!<br>Funktion AddTask fehlt Parameter 1!"));
	   return;
	}

	$db = OpenDB();
	# Projektnummer und Projektname ermitteln
	$query = "select plan.pl_prnum, project.pr_name from plan, project ";
	$query .= "where plan.pl_num = $ta_plnum and ";
	$query .= "project.pr_num = plan.pl_prnum";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];
	$pr_name = $data[1];

	# Finden des vorhergehenden Tasks um den Level vorzuschlagen.
	$query = "select ta_level, ta_meeting, ta_phase from task where ta_plnum = $ta_plnum and ";
	$query .= "ta_id < $ta_id order by ta_id desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	if (numrowsDB($result) > 0) {
	   $data = fetchDB($result, 0);
	   $level = $data[0];
	   $ta_meeting = $data[1];
	   $ta_phase = $data[2];

	   if ($level == 1)
	      $level = 2;
	} else {
	   $level = 1;
	   $ta_meeting = 0;
	   $ta_phase = 0;
	}
?>
<br>
<form name="Task" action="plan.php" method="post">
<input type="hidden" name="ta_plnum" value="<? echo "$ta_plnum"; ?>">
<input type="hidden" name="headline" value="20">
<input type="hidden" name="menu" value="<? echo "$menu"; ?>">
<input type="hidden" name="ta_id" value="<? echo "$ta_id"; ?>">
<input type="hidden" name="func" value="SaveTask">
<?
	if (!$verrmodul)
	   echo "<input type=\"hidden\" name=\"ta_risiko\" value=\"0\">\n";
?>
<table class="input">
   <tr>
      <th class="sel" colspan=2><? Output($db, 1, "Projekt:"); echo "$pl_prnum $pr_name"; ?></th>
   </tr>
   <tr>
      <td>Level:</td>
      <td>
<?
	echo "<input type=\"text\" class=\"inputmust\" name=\"ta_level\" value=\"$level\" ";

	if ($ta_meeting)
	   echo "onBlur=\"NumRange(this,1,$level)\" ";
	else
	   echo "onBlur=\"NumRange(this,1,99)\" ";

	echo "size=2 maxlength=2>";
?>
      </td>
   </tr>
   <tr>
      <td><? Output($db, 2, "Taskname:"); ?></td>
      <td><input type="text" class="inputmust" name="ta_name" size=40 maxlength=50></td>
   </tr>
<?
        if (!$pmlight) { ?>
   <tr>
      <td><? Output($db, 3, "Farbe:"); ?></td>
      <td><input type="text" class="inputmust" name="ta_color" value="ffffcc" size=8 maxlength=6>
<?php
	   echo "<button type=\"button\" onClick=\"javascript:open_window('plan.php?unum=$unum&rstufe=$rstufe&header=1&func=GetColor', 'Farbwahl', 217, 57)\">";
	   echo "<img src=\"image/coloredit.png\" border=0 width=15 height=15 alt=\"Farbwahl\"></button>";
	   echo "</td>\n</tr>\n";
	} else {
	   echo "<input type=\"hidden\" name=\"ta_color\" value=\"ffffcc\">\n";
	}
?>
   <tr>
      <td><? Output($db, 4, "Meilenstein:"); ?></td>
      <td><input type="checkbox" name="ta_meeting" value="1" onChange="javascript:if (this.checked == true) {document.Task.ende.value = document.Task.start.value;}"></td>
   </tr>
<?php
	if ($phase == 1) {
	   echo "<tr><td>" . GetMessage($db, 5, "Phase:") . "</td>\n<td>";
	   $query = "select kp_num, kp_phase from key_phase order by kp_num";
	   $result = QueryDB($db, $query);

	   if (!result)
	      return;

	   $numrows = numrowsDB($result);
	   $row = 0;
	   echo "<select name=\"ta_phase\">\n";

	   while ($row < $numrows) {
	      $data = fetchDB($result, $row);
	      $kp_num = $data[0];
	      $kp_phase = $data[1];

	      if ($kp_num == $ta_phase)
	         echo "<option value=\"$kp_num\" selected>$kp_num. $kp_phase</option>\n";
	      else
	         echo "<option value=\"$kp_num\">$kp_num. $kp_phase</option>\n";

	      $row++;
	   }

	   echo "</td></tr>\n";
	} else {
	   $ta_phase = 0;
	}
?>
   <tr>
      <td><? Output($db, 6, "Startdatum (%s):", $VisualDate); ?></td>
      <td><input type="text" class="inputmust" name="start" onChange="javascript:CheckDate(this, false)" onBlur="javascript:if (document.Task.ta_meeting.checked == true) {document.Task.ende.value = this.value;}" size=10 maxlength=10>
          <input type="button" value="..." onClick="javascript:open_window('calendar.php?header=1&target=window.opener.document.Task.start', 'Calendar', 200, 250)">
      </td>
   </tr>
   <tr>
      <td><? Output($db, 7, "Endedatum (%s):", $VisualDate); ?></td>
      <td><input type="text" class="inputmust" name="ende" onChange="javascript:var stat = CheckDate(this, false);if (stat == true) {CheckDateOrder(document.Task.start, this);}" size=10 maxlength=10>
	  <input type="button" value="..." onClick="javascript:open_window('calendar.php?header=1&target=window.opener.document.Task.ende', 'Calendar', 200, 250)">
      </td>
   </tr>
<?
	if ($verrmodul) {
?>
   <tr>
      <td><? Output($db, 8, "Risikoaufschlag:"); ?></td>
      <td><input type="text" name="ta_risiko" value="0" onBlur="javascript:NumRange(this,0,100)" size="3" maxlength=3>%</td>
   </tr>
<?
	}
?>
   <tr>
      <td><? Output($db, 9, "Bereits erledigt:"); ?></td>
      <td><input type="text" name="ta_complete" value="0" size=3 maxlength=3>%</td>
   </tr>
   <tr>
      <td><? Output($db, 10, "Priorit&auml;t:"); ?></td>
      <td><select name="ta_priority">
             <option value="0"><? Output($db, 11, "Niedrig"); ?></option>
	     <option value="1" selected><? Output($db, 12, "Normal"); ?></option>
	     <option value="2"><? Output($db, 13, "Hoch"); ?></option>
	  </select>
      </td>
   </tr>
   <tr>
      <td><? Output($db, 14, "Abh&auml;ngigkeit:"); ?></td>
      <td><select name="ta_depend">
             <option selected></option>
<?php
	SelectTask($ta_plnum, true);
	closeDB($db);
?>
          </select>
	  <select name="ta_deptype">
	     <option value="2"><? Output(-1, 15, "Ende-Beginn"); ?></option>
	     <option value="3"><? Output(-1, 16, "Ende-Ende"); ?></option>
	     <option value="4"><? Output(-1, 17, "Beginn-Ende"); ?></option>
	     <option value="1"><? Output(-1, 18, "Beginn-Beginn"); ?></option>
	  </select>
      </td>
   </tr>
   <tr>
      <td valign="top"><? Output(-1, 19, "Kommentar:"); ?></td>
      <td><textarea name="ta_notiz" rows=5 cols=60></textarea></td>
   </tr>
   <tr>
      <td class="selnf" colspan=2>
         <table border=0 cellspacing=0 cellpadding=0><tr><td>
<?
	Button(GetMessage(-1, 20, "Task Speichern"), "Task");
	echo "</td><td>&nbsp;&nbsp;</td><td>";
	ButtonLink(GetMessage(-1, 21, "Zur&uuml;ck"), "plan.php", "editplan=$ta_plnum&menu=$menu&headline=20");
?>
        </td></tr></table>
      </td>
   </tr>
</table>
<br>
<?php
	echo "</form>\n";
}

# Folgende Funktion zeigt die Erfassungsmaske fuer einen Task an. Es muss
# die interne Datensatznummer des Plans uebergeben werden auf die sich der
# Task bezieht.
#
function EditTask($ta_num) {
	global $dtformatshort;
	global $VisualDate;
	global $verrmodul;
	global $ab_datum;

	$menu = $_REQUEST['menu'];
	global $unum;
	global $rstufe;
	global $phase;
	global $numphase;
	global $pmlight;

	$db = OpenDB();
	$query = "select ta_plnum, ta_id, ta_depend, ta_deptype, ta_name, ";
	$query .= "ta_color, ta_meeting, ta_start, ta_duration, ta_complete, ";
	$query .= "ta_priority, ta_level, ta_phase, ta_notiz, ta_risiko from task ";
	$query .= "where ta_num = $ta_num";

	$result = QueryDB($db, $query);
	$numrows = numrowsDB($result);

	if ($numrows != 1) {
	   Error(GetMessage($db, 340, "Interner Fehler: Task \"%d\" existiert nicht!", $ta_num));
	   return;
	}

	$data = fetchDB($result, 0);
	$ta_plnum = $data[0];
	$ta_id = $data[1];
	$ta_depend = $data[2];
	$ta_deptype = $data[3];
	$ta_name = $data[4];
	$ta_color = $data[5];
	$ta_meeting = $data[6];
	$ta_start = $data[7];
	$ta_duration = $data[8];
	$ta_complete = $data[9];
	$ta_priority = $data[10];
	$ta_level = $data[11];
	$ta_phase = $data[12];
	$ta_notiz = $data[13];
	$ta_risiko = $data[14];
	$color = dechex($ta_color);
	$len = strlen($color);

	while ($len < 6) {
	   $color = "0" . $color;
	   $len++;
	}

	# Ermitteln, ob der Task bereits Mitarbeiter zugewiesen hat. In
	# diesem Fall darf der Level nicht geaendert werden und es darf
	# kein Meilenstein werden.
	$query = "select count(*) from allocation where al_task = $ta_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$anz = $data[0];

	$query = "select plan.pl_prnum, project.pr_name from plan, project ";
	$query .= "where plan.pl_num = $ta_plnum and ";
	$query .= "project.pr_num = plan.pl_prnum";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];
	$pr_name = $data[1];
	echo "<p class=\"cry\">" . GetMessage($db, 1, "Projekt:") . " $pl_prnum $pr_name</p>";
	# Datum des letzten Teilprojektabschluss ermitteln
	$query = "select ab_datum from abschluss where ";
	$query .= "ab_prnum = $pl_prnum order by ab_datum desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	if (numrowsDB($result) > 0) {
	   $data = fetchDB($result, 0);
	   $ab_datum = $data[0];
	} else
	   $ab_datum = 0;

	# Start des Tasks ermitteln. Gibt es breits IST-Buchungen auf
	# diesen Plan, dann darf der Start des Tasks nicht nach die erste
	# IST-Buchung geschoben werden.
	$query = "select wd_datum from wdone where ";
	$query .= "wd_task = $ta_num and wd_datum <= $ta_start ";
	$query .= "order by wd_datum";

	if (!($reswd = QueryDB($db, $query)))
	   return;

	$rows = numrowsDB($reswd);

	if ($rows > 0) {
	   $data = fetchDB($reswd, 0);
	   $wd_datum = $data[0];
	}
	# Finden der folgenden Tasks um im Falle eines Ordners automatisch
	# das richtige Beginn- und Endedatum zu setzen.
	$query = "select ta_level, ta_meeting, ta_start,";
	$query .= "ta_start+ta_duration*86400 from task where ";
	$query .= "ta_plnum = $ta_plnum and ta_id > $ta_id order by ta_id";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$tstart = 0;
	$tend = 0;

	if (($rows = numrowsDB($result)) > 0) {
	   $j = 0;

	   while ($j < $rows) {
	      $data = fetchDB($result, $j);
	      $xlevel = $data[0];
	      $xmeeting = $data[1];
	      $xstart = $data[2];
	      $xend = $data[3];

	      if ($xlevel <= $ta_level)
	         break;

	      if ($tstart == 0 || $tstart > $xstart)
	         $tstart = $xstart;

	      if ($tend < $xend) {
	         if ($xmeeting) {
	            if ($tend < $xstart)
		       $tend = $xstart;
		 } else
	            $tend = $xend;
	      }

	      $j++;
	   }
	}
?>
<br>
<form name="Task" action="plan.php" method="post">
<input type="hidden" name="ta_num" value="<? echo "$ta_num"; ?>">
<input type="hidden" name="ta_plnum" value="<? echo "$ta_plnum"; ?>">
<input type="hidden" name="headline" value="20">
<input type="hidden" name="menu" value="<? echo "$menu"; ?>">
<input type="hidden" name="ta_id" value="<? echo "$ta_id"; ?>">
<input type="hidden" name="folder" value="0">
<?
	if ($tstart > 0) {
	   echo "<input type=\"hidden\" name=\"start\" value=\"". gmdate($dtformatshort, $tstart) . "\">\n";
	   echo "<input type=\"hidden\" name=\"folder\" value=\"1\">\n";
	} else
	   echo "<input type=\"hidden\" name=\"folder\" value=\"0\">\n";

	if ($tend > 0)
	   echo "<input type=\"hidden\" name=\"ende\" value=\"". gmdate($dtformatshort, $tend) . "\">\n";

	if ($anz > 0 || $tstart > 0 || $tend > 0)
	   echo "<input type=\"hidden\" name=\"ta_level\" value=\"$ta_level\">\n";

	if (!$verrmodul)
	   echo "<input type=\"hidden\" name=\"ta_risiko\" value=\"0\">\n";
?>
<input type="hidden" name="func" value="SaveTask">

<table class="input">
   <tr>
      <td>Level:</td>
<?
	if ($anz > 0 || $tstart > 0 || $tend > 0) {
?>
      <td><b><? echo "$ta_level"; ?></b></td>
<?	} else { ?>
      <td><input type="text" class="inputmust" name="ta_level" value="<? echo "$ta_level"; ?>" onBlur="NumRange(this,1,99)" size=2 maxlength=2></td>
<?	} ?>
   </tr>
   <tr>
      <td>Taskname:</td>
      <td><input type="text" class="inputmust" name="ta_name" value="<? echo htmlentities($ta_name); ?>" size=40 maxlength=50></td>
   </tr>
<?
	if (!$pmlight) { ?>
   <tr>
      <td>Farbe:</td>
      <td><input type="text" name="ta_color" value="<? echo "$color"; ?>" size=8 maxlength=6>
<?php
	   echo "<button type=\"button\" onClick=\"javascript:open_window('plan.php?header=1&func=GetColor', 'Farbwahl', 217, 57)\">";
	   echo "<img src=\"image/coloredit.png\" border=0 width=15 height=15 alt=\"Farbwahl\"></button>";
	   echo "</td></tr>\n";
	} else {
	   echo "<input type=\"hidden\" name=\"ta_color\" value=\"ffffcc\">\n";
	}
?>
   <tr>
      <td>Meilenstein:</td>
<?php
	if ($ta_meeting) {
           echo "<td><input type=\"checkbox\" name=\"ta_meeting\" value=\"1\" checked ";
	} else {
           echo "<td><input type=\"checkbox\" name=\"ta_meeting\" value=\"1\" ";
	}

	echo "onChange=\"javascript:if (this.checked == true) {document.Task.ende.value = document.Task.start.value;}\" ";

	if ($anz > 0  || $tstart > 0 || $tend > 0)
	   echo "disabled";

	echo "></td>\n";
?>
   </tr>
<?php
	if ($phase == 1) {
	   echo "<tr><td>Phase:</td>\n<td>";
	   $query = "select kp_num, kp_phase from key_phase order by kp_num";
	   $result = QueryDB($db, $query);

	   if (!$result)
	      return;

	   $numrows = numrowsDB($result);
	   $row = 0;
	   echo "<select name=\"ta_phase\">\n";

	   while ($row < $numrows) {
	      $data = fetchDB($result, $row);
	      $kp_num = $data[0];
	      $kp_phase = $data[1];

	      if ($ta_phase == $kp_num)
	         echo "<option value=\"$kp_num\" selected>$kp_num. $kp_phase</option>\n";
	      else
	         echo "<option value=\"$kp_num\">$kp_num. $kp_phase</option>\n";

	      $row++;
	   }

	   echo "</td></tr>\n";
	}
?>
   <tr>
      <td><? Output($db, 6, "Startdatum (%s):", $VisualDate); ?></td>
<?php
	# Wenn $tstart > 0 ist, dann handelt es sich um einen Ordner!
	if ($tstart > 0)
	   $tm = gmdate($dtformatshort, $tstart);
	else
	   $tm = gmdate($dtformatshort, $ta_start);

	echo "      <td><input type=\"text\" class=\"inputmust\" ";

	if ($tstart > 0 || ($tstart > 0 && $tstart <= $ab_datum) || ($tstart <= 0 && $ta_start <= $ab_datum)) {
	   echo "disabled ";
	   $disabled = true;
	} else {
	   echo "onChange=\"javascript:var stat = CheckDate(this, false);if (stat == true && document.Task.ta_meeting.checked == true) {document.Task.ende.value = this.value;}\" ";
	   $disabled = false;
	}

	echo "name=\"start\" value=\"$tm\" size=10 maxlength=10>\n";

	if ($tend > 0)
	   $te = $tend;
	else
	   $te = $ta_start + ($ta_duration * 86400);

	$tem = gmdate($dtformatshort, $te);

	if ($tstart == 0 && !$disabled) {
?>
          <input type="button" value="..." onClick="javascript:open_window('calendar.php?header=1&edit=<? echo "$ta_start"; ?>&target=window.opener.document.Task.start', 'Calendar', 200, 250); document.Task.start.focus()">
<?
	} else if ($tstart == 0) {
?>
          <input type="hidden" name="start" value="<? echo "$tm"; ?>">
<?
	}
?>
      </td>
   </tr>
   <tr>
      <td><? Output($db, 7, "Endedatum (%s):", $VisualDate); ?></td>
      <td><input type="text" class="inputmust" name="ende" value="<? echo "$tem"; ?>" <? if ($tend > 0) echo "disabled"; ?> onChange="javascript:erg = CheckDate(this, false);if (erg == true) {CheckDateOrder(document.Task.start, this);}" size=10 maxlength=10>
<?
	if ($tend == 0) {
?>
          <input type="button" value="..." onClick="javascript:open_window('calendar.php?header=1&target=window.opener.document.Task.ende', 'Calendar', 200, 250); document.Task.ende.focus()">
<?
	} else {
?>
          <input type="hidden" name="ende" value="<? echo "$tem"; ?>">
<?
	}
?>
      </td>
   </tr>
<?
	if ($verrmodul) {
?>
   <tr>
      <td>Risikoaufschlag:</td>
      <td><input type="text" name="ta_risiko" value="<? echo "$ta_risiko"; ?>" onBlur="javascript:NumRange(this,0,100)" size="3" maxlength=3>%</td>
   </tr>
<?
	}
?>
   <tr>
      <td>Bereits erledigt:</td>
      <td><input type="text" name="ta_complete" value="<? echo "$ta_complete"; ?>" size=3 maxlength=3>%</td>
   </tr>
   <tr>
      <td>Priorit&auml;t:</td>
      <td><select name="ta_priority">
             <option value="0" <? if ($ta_priority == 0) echo "selected"; ?>>Niedrig</option>
	     <option value="1" <? if ($ta_priority == 1) echo "selected"; ?>>Normal</option>
	     <option value="2" <? if ($ta_priority == 2) echo "selected"; ?>>Hoch</option>
	  </select>
      </td>
   </tr>
   <tr>
      <td>Abh&auml;ngigkeit:</td>
      <td colspan=2><select name="ta_depend">
<?php
	if (strlen($ta_depend) == 0 || $ta_depend == 0) {
	   echo "<option selected></option>\n";
	} else {
	   echo "<option></option>\n";
	}

	$query = "select ta_num, ta_name, ta_id, ta_level, ta_depend, ta_meeting, ta_phase from task where ta_plnum = $ta_plnum order by ta_id";
	$result = QueryDB($db, $query);
	$numrows = numrowsDB($result);
	$row = 0;
	$snum = "1";
	$olevel = 0;
	$db2 = OpenDB();

	while ($row < $numrows) {
	   $data = fetchDB($result, $row);
	   $num = $data[0];
	   $name = $data[1];
	   $id = $data[2];
	   $level = $data[3];
	   $depend = $data[4];
	   $meeting = $data[5];
	   $tphase = $data[6];

	   $query = "select ta_level from task where ta_plnum = $ta_plnum and ta_id > $id order by ta_id";
	   $result2 = QueryDB($db2, $query);
	   $nr = numrowsDB($result2);

	   if ($nr > 0) {
	      $data = fetchDB($result2, 0);
	      $xlevel = $data[0];
	   } else {
	      $xlevel = $ta_level;
	   }

	   if ($olevel == 0) {
	      $lev = 0;
	      $olevel = $level;
	      $dir = -3;
	   } else if ($olevel < $level) {
	      $lev = $level - 1;
	      $olevel = $level;
	      $dir = -3;
	   } else if ($olevel == $level) {
	      $lev = $level - 1;
	      $dir = 0;
	   } else if ($olevel > $level) {
	      $lev = $level - 1;
	      $olevel = $level;
	      $dir = -1;
	   }

	   $snum = kNumber($snum, $lev, $dir);

	   if ($phase == 1 && $numphase == 1) {
	      $sarr = explode(".", $snum);
	      $sarr[0] = $tphase;
	      $snum = implode(".", $sarr);
	   }

	   if ($ta_depend > 0 && $ta_depend == $id) {
	      echo "<option value=\"$id\" selected>$snum $name</option>\n";
	   } else {
	      if (!$meeting && $level > 1 && $xlevel <= $level)
	         echo "<option value=\"$id\">$snum $name</option>\n";
	   }

	   $row++;
	}
?>
          </select>
	  <select name="ta_deptype">
	     <option value="2" <? if ($ta_deptype == 2) echo "selected"; ?>>Ende-Beginn</option>
	     <option value="3" <? if ($ta_deptype == 3) echo "selected"; ?>>Ende-Ende</option>
	     <option value="4" <? if ($ta_deptype == 4) echo "selected"; ?>>Beginn-Ende</option>
	     <option value="1" <? if ($ta_deptype == 1) echo "selected"; ?>>Beginn-Beginn</option>
	  </select>
      </td>
   </tr>
   <tr>
      <td valign="top">Kommentar:</td>
      <td colspan=2><textarea name="ta_notiz" rows=5 cols=60><? echo htmlentities($ta_notiz); ?></textarea></td>
   </tr>
   <tr>
      <td class="selnf" colspan=2>
         <table border=0 cellspacing=0 cellpadding=0><tr><td>
<?
	Button("Task Speichern", "Task");
	echo "</td><td>&nbsp;&nbsp;</td><td>";
	ButtonLink("Zur&uuml;ck", "plan.php", "editplan=$ta_plnum&menu=$menu&headline=20");
?>
        </td></tr></table>
      </td>
   </tr>
</table>
<br>
<?php
	echo "</form>\n";
	closeDB($db);
}

# Folgende Funktion laesst die Auswahl einer Farbe zu, die dann in ein
# bestimmtes Feld der Maske "Task" geschrieben wird (function AddTask).
# Die Funktion wird ueber ein Java Script innerhalb eines eigenen Fensters
# aufgerufen. Neben einer Farbtafel enthaelt das Fenster noch einen Button
# ueber den es sich schliessen laesst.
#
function GetColor() {
?>
<map name="farbe">
<area shape="rect" coords="1,1,26,10" href="javascript:Farb('255','128','128')">
<area shape="rect" coords="28,1,53,10" href="javascript:Farb('255','255','128')">
<area shape="rect" coords="55,1,80,10" href="javascript:Farb('128','255','128')">
<area shape="rect" coords="82,1,107,10" href="javascript:Farb('0','255','128')">
<area shape="rect" coords="109,1,134,10" href="javascript:Farb('128','255','255')">
<area shape="rect" coords="136,1,161,10" href="javascript:Farb('0','128','255')">
<area shape="rect" coords="163,1,188,10" href="javascript:Farb('255','128','192')">
<area shape="rect" coords="190,1,215,10" href="javascript:Farb('255','128','255')">
<area shape="rect" coords="1,12,26,21" href="javascript:Farb('255','0','0')">
<area shape="rect" coords="28,12,53,21" href="javascript:Farb('255','255','0')">
<area shape="rect" coords="55,12,80,21" href="javascript:Farb('128','255','0')">
<area shape="rect" coords="82,12,107,21" href="javascript:Farb('0','255','64')">
<area shape="rect" coords="109,12,134,21" href="javascript:Farb('0','255','255')">
<area shape="rect" coords="136,12,161,21" href="javascript:Farb('0','128','192')">
<area shape="rect" coords="163,12,188,21" href="javascript:Farb('128','128','192')">
<area shape="rect" coords="190,12,215,21" href="javascript:Farb('255','0','255')">
<area shape="rect" coords="1,23,26,32" href="javascript:Farb('128','64','64')">
<area shape="rect" coords="28,23,53,32" href="javascript:Farb('255','128','64')">
<area shape="rect" coords="55,23,80,32" href="javascript:Farb('0','255','0')">
<area shape="rect" coords="82,23,107,32" href="javascript:Farb('0','128','128')">
<area shape="rect" coords="109,23,134,32" href="javascript:Farb('0','64','128')">
<area shape="rect" coords="136,23,161,32" href="javascript:Farb('128','128','255')">
<area shape="rect" coords="163,23,188,32" href="javascript:Farb('128','0','64')">
<area shape="rect" coords="190,23,215,32" href="javascript:Farb('255','0','128')">
<area shape="rect" coords="1,34,26,43" href="javascript:Farb('128','0','0')">
<area shape="rect" coords="28,34,53,43" href="javascript:Farb('255','128','0')">
<area shape="rect" coords="55,34,80,43" href="javascript:Farb('0','128','0')">
<area shape="rect" coords="82,34,107,43" href="javascript:Farb('0','128','64')">
<area shape="rect" coords="109,34,134,43" href="javascript:Farb('0','0','255')">
<area shape="rect" coords="136,34,161,43" href="javascript:Farb('0','0','160')">
<area shape="rect" coords="163,34,188,43" href="javascript:Farb('128','0','128')">
<area shape="rect" coords="190,34,215,43" href="javascript:Farb('128','0','255')">
<area shape="rect" coords="1,45,26,54" href="javascript:Farb('64','0','0')">
<area shape="rect" coords="28,45,53,54" href="javascript:Farb('128','64','0')">
<area shape="rect" coords="55,45,80,54" href="javascript:Farb('0','64','0')">
<area shape="rect" coords="82,45,107,54" href="javascript:Farb('0','64','64')">
<area shape="rect" coords="109,45,134,54" href="javascript:Farb('0','0','128')">
<area shape="rect" coords="136,45,161,54" href="javascript:Farb('0','0','64')">
<area shape="rect" coords="163,45,188,54" href="javascript:Farb('64','0','64')">
<area shape="rect" coords="190,45,215,54" href="javascript:Farb('64','0','128')">
<area shape="rect" coords="1,56,26,65" href="javascript:Farb('0','0','0')">
<area shape="rect" coords="28,56,53,65" href="javascript:Farb('128','128','0')">
<area shape="rect" coords="55,56,80,65" href="javascript:Farb('128','128','64')">
<area shape="rect" coords="82,56,107,65" href="javascript:Farb('128','128','128')">
<area shape="rect" coords="109,56,134,65" href="javascript:Farb('64','128','128')">
<area shape="rect" coords="136,56,161,65" href="javascript:Farb('192','192','192')">
<area shape="rect" coords="163,56,188,65" href="javascript:Farb('64','64','64')">
<area shape="rect" coords="190,56,215,65" href="javascript:Farb('255','255','255')">
</map>
<img src="image/farben.png" width="217" height="67" border="0" vspace="3" alt="" usemap="#farbe">
<form name="schliessen">
<?
	ButtonProg("Schliessen", "self.close()");
//   <input type="button" name="close" value="Schliessen" onClick="javascript:self.close()">
	echo "</form>\n";
}

# Die folgenden zwei Funktionen loeschen einen bestehenden Plan
# und alle damit verknpften Tasks. Neben dem Superuser darf das auch
# vom Projektleiter durchgefuehrt werden.
#
function AskDelete($pl_num) {
	global $phase;

	$headline = $_REQUEST['headline'];
	$menu = $_REQUEST['menu'];
	$nav = "pl_num=$pl_num&menu=$menu&func=DeletePlan&headline=21";
?>
<br>
<form action="plan.php" method="post">
<table border=2 class="alarm">
   <tr><td colspan=2><big>Warnung!</big><br><br>
           Sie sind im Begriff alle erfassten Tasks dieses Plans zu
	   l&ouml;schen!<br><br>
	   Wollen Sie wirklich diesen Plan mit allen Daten
	   unwiederbringlich l&ouml;schen?<br>
      </td>
   </tr>
   <tr>
      <td><center><input type="button" name="yes" value="L&ouml;schen" onClick="javascript:MoveTo('plan.php','yes=yes&<? echo "$nav"; ?>')"></center></td>
      <td><center><input type="button" name="no" value="Abbruch" onClick="javascript:MoveTo('plan.php','no=no&<? echo "$nav"; ?>')"></center></td>
   </tr>
</table>
</form>
<?php
}

function DeletePlan() {
	global $phase;

	$pl_num = $_REQUEST['pl_num'];
	$db = OpenDB();
	QueryDB($db, "begin");
	$query = "select ta_num from task where ta_plnum = $pl_num";
	$result = QueryDB($db, $query);

	if (!result) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	$numrows = numrowsDB($result);
	$row = 0;

	while ($row < $numrows) {
	   $data = fetchDB($result, $row);
	   $ta_num = $data[0];
	   $query = "delete from allocation where al_task = $ta_num";

	   if (!QueryDB($db, $query)) {
	      QueryDB($db, "rollback");
	      closeDB($db);
	      return false;
	   }

	   $row++;
	}

	$query = "delete from task where ta_plnum = $pl_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	$query = "delete from plan where pl_num = $pl_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(101, "plan.php: DeletePlan: pl_num=$pl_num", $db);
	closeDB($db);
	return true;
}

# Die folgenden zwei Funktionen loeschen einen bestehenden Task
# und alle damit verknpften Mitarbeiter. Neben dem Superuser darf das auch
# vom Projektleiter durchgefuehrt werden.
#
function AskDeleteTask($ta_num) {
	global $phase;

	$headline = $_REQUEST['headline'];
	$menu = $_REQUEST['menu'];
	$ta_plnum = $_REQUEST['ta_plnum'];
	$nav = "ta_num=$ta_num&ta_plnum=$ta_plnum&func=DeleteTask&menu=$menu&headline=21";

	$db = OpenDB();
	$query = "select plan.pl_prnum, project.pr_name from plan, project ";
	$query .= "where plan.pl_num = $ta_plnum and project.pr_num = plan.pl_prnum";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];
	$pr_name = $data[1];
	echo "<p class=\"cry\">Projekt: $pl_prnum $pr_name</p>";
	closeDB($db);
?>
<br>
<form action="plan.php" method="post">
<table border=2 class="alarm">
   <tr><td colspan=2><big>Warnung!</big><br><br>
           Sie sind im Begriff einen Task mit allen seinen Abh&auml;ngigkeiten
	   zu l&ouml;schen!<br><br>
	   Wollen Sie wirklich diesen Task unwiederbringlich l&ouml;schen?<br>
      </td>
   </tr>
   <tr>
      <td><center><input type="button" name="yes" value="L&ouml;schen" onClick="javascript:MoveTo('plan.php','yes=yes&<? echo "$nav"; ?>')"></center></td>
      <td><center><input type="button" name="no" value="Abbruch" onClick="javascript:MoveTo('plan.php','no=no&<? echo "$nav"; ?>')"></center></td>
   </tr>
</table>
</form>
<?php
}

function DeleteTask() {
	global $phase;

	$ta_num = $_REQUEST['ta_num'];

	if (!isset($ta_num) || $ta_num < 1) {
	   Error("Interner Fehler: DeleteTask: Tasknummer fehlt oder ist ung&uuml;ltig!");
	   return false;
	}

	$db = OpenDB();
	# Fuer das E-Journal brauchen wir die Plan- und Projektnummer!
	$query = "select pl_num, pl_prnum, ta_name from task, plan where ";
	$query .= "pl_num = ta_plnum and ta_num = $ta_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$pl_num = $data[0];
	$pl_prnum = $data[1];
	$ta_name = $data[2];

	QueryDB($db, "begin");
	$query = "delete from allocation where al_task = $ta_num";
	$result = QueryDB($db, $query);

	if (!$result) {
	   QueryDB($db, "rollback");
	   Error("SQL-Error: $query");
	   closeDB($db);
	   return false;
	}

	$query = "delete from task where ta_num = $ta_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   Error("SQL-Error: $query");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(100, "plan.php: DeleteTask: ta_num=$ta_num $ta_name, pl_num=$pl_num, Projekt: $pl_prnum", $db);
	closeDB($db);
	return true;
}

# Die folgenden zwei Funktionen loeschen einen bestehenden Task
# und alle damit verknpften Mitarbeiter. Neben dem Superuser darf das auch
# vom Projektleiter durchgefuehrt werden.
#
function AskDeleteMa() {
	global $phase;
	global $dtformatshort;

	$headline = $_REQUEST['headline'];
	$menu = $_REQUEST['menu'];
	$pl_num = $_REQUEST['pl_num'];
	$al_task = $_REQUEST['al_task'];
	$ressource = $_REQUEST['ressource'];
	$nav = "al_task=$al_task&pl_num=$pl_num&ressource=$ressource&func=DeleteMa&menu=$menu&headline=$headline";

	$db = OpenDB();
	$query = "select plan.pl_prnum, project.pr_name from plan, project ";
	$query .= "where plan.pl_num = $pl_num and project.pr_num = plan.pl_prnum";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];
	$pr_name = $data[1];
	echo "<p class=\"cry\">Projekt: $pl_prnum $pr_name</p>";

	$query = "select ta_name, ta_start, ta_duration from task ";
	$query .= "where ta_num = $al_task";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$ta_name = $data[0];
	$ta_start = $data[1];
	$ta_duration = $data[2];

	$query = "select am_hours, am_role, am_nname, am_vname ";
	$query .= "from allocmi where am_task = $al_task and am_ressource = $ressource";
	$result = QueryDB($db, $query);
	$rows = 0;
	$numrows = numrowsDB($result);

?>
<br>
<form action="plan.php" method="post">
<table border=2 class="alarm">
   <tr><td colspan=2><big>Warnung!</big><br><br>
           Sie sind im Begriff einen Mitarbeiter von einem Task
	   zu l&ouml;schen!<br>
	   <center><table border=1><tr>
	      <td class="tbhead">Taskname</td>
	      <td class="tbhead">Dauer</td>
	      <td class="tbhead">Start</td></tr>
<?php
        echo "<tr><td>$ta_name</td>\n";
        echo "<td>$ta_duration</td>\n";
        $dt = gmdate($dtformatshort, $ta_start);
        echo "<td>$dt</td></tr>\n";
        echo "</table></center>\n";

        echo "<center><p>";

        while ($rows < $numrows) {
           $data = fetchDB($result, $rows);
           $am_hours = $data[0];
           $am_role = $data[1];
           $am_nname = $data[2];
           $am_vname = $data[3];

           if ($rows == 0) {
              echo "$am_nname $am_vname, $am_role: ";
              printf("%s", FormatNum($am_hours, 3));
           }
           else
              printf(", %s", FormatNum($am_hours, 3));

           $rows++;
        }

        echo "</p></center>\n";
        closeDB($db);
?>
	   Wollen Sie wirklich diesen Mitarbeiter unwiederbringlich l&ouml;schen?<br>
      </td>
   </tr>
   <tr>
      <td><center><input type="button" name="yes" value="L&ouml;schen" onClick="javascript:MoveTo('plan.php','yes=yes&<? echo "$nav"; ?>')"></center></td>
      <td><center><input type="button" name="no" value="Abbruch" onClick="javascript:MoveTo('plan.php','no=no&<? echo "$nav"; ?>')"></center></td>
   </tr>
</table>
</form>
<?php
}

function DeleteMa() {
	$al_task = $_REQUEST['al_task'];
	$ressource = $_REQUEST['ressource'];

	$db = OpenDB();
	QueryDB($db, "begin");
	$query = "delete from allocation where al_task = $al_task and ";
	$query .= "al_ressource = $ressource";
	$result = QueryDB($db, $query);

	if (!result) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(105, "plan.php: DeleteMa: ressource=$ressource; task=$al_task", $db);
	closeDB($db);
	return true;
}

# Folgende Funktion wird von SaveTask() aufgerufen.
# Der Aufruf erfolgt, wenn bei einem Task das Startdatum so geaendert
# wurde, dass es gegenueber dem Alten in der Vergangenheit liegt. Ist das
# der Fall, koennen die betroffenen Perioden der zugeordneten Mitarbeiter
# geloescht werden.
#
function AskObsoleteMA() {
	global $menu;
	global $headline;
	global $phase;

	$ta_num = $_REQUEST['ta_num'];
	$ta_plnum = $_REQUEST['ta_plnum'];
	$ta_id = $_REQUEST['ta_id'];
	$ta_level = $_REQUEST['ta_level'];
	$ta_name = $_REQUEST['ta_name'];
	$ta_color = $_REQUEST['ta_color'];
	$ta_meeting = $_REQUEST['ta_meeting'];
	$start = $_REQUEST['start'];
	$ende = $_REQUEST['ende'];
	$ta_duration = $_REQUEST['ta_duration'];
	$ta_complete = $_REQUEST['ta_complete'];
	$ta_priority = $_REQUEST['ta_priority'];
	$ta_depend = $_REQUEST['ta_depend'];
	$ta_deptype = $_REQUEST['ta_deptype'];
	$ta_notiz = $_REQUEST['ta_notiz'];

	if ($phase)
	   $ta_phase = $_REQUEST['ta_phase'];
	else
	   $ta_phase = 0;

	if (!isset($ta_meeting))
	   $ta_meeting = 0;

	echo "<form name=\"obsolete\" action=\"plan.php\" method=\"post\">\n";
	echo "<input type=\"hidden\" name=\"ta_num\" value=\"$ta_num\">\n";
	echo "<input type=\"hidden\" name=\"ta_plnum\" value=\"$ta_plnum\">\n";
	echo "<input type=\"hidden\" name=\"ta_id\" value=\"$ta_id\">\n";
	echo "<input type=\"hidden\" name=\"ta_level\" value=\"$ta_level\">\n";
	echo "<input type=\"hidden\" name=\"ta_name\" value=\"$ta_name\">\n";
	echo "<input type=\"hidden\" name=\"ta_color\" value=\"$ta_color\">\n";
	echo "<input type=\"hidden\" name=\"ta_meeting\" value=\"$ta_meeting\">\n";
	echo "<input type=\"hidden\" name=\"ta_duration\" value=\"$ta_duration\">\n";
	echo "<input type=\"hidden\" name=\"ta_complete\" value=\"$ta_complete\">\n";
	echo "<input type=\"hidden\" name=\"ta_priority\" value=\"$ta_priority\">\n";
	echo "<input type=\"hidden\" name=\"ta_depend\" value=\"$ta_depend\">\n";
	echo "<input type=\"hidden\" name=\"ta_deptype\" value=\"$ta_deptype\">\n";
	echo "<input type=\"hidden\" name=\"ta_phase\" value=\"$ta_phase\">\n";
	echo "<input type=\"hidden\" name=\"ta_notiz\" value=\"$ta_notiz\">\n";
	echo "<input type=\"hidden\" name=\"start\" value=\"$start\">\n";
	echo "<input type=\"hidden\" name=\"ende\" value=\"$ende\">\n";
	echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
	echo "<input type=\"hidden\" name=\"headline\" value=\"$headline\">\n";
	echo "<input type=\"hidden\" name=\"func\" value=\"SaveObsoleteTask\">\n";
?>
<center>
<table border=2 class="alarm" width="50%">
   <tr>
      <td colspan=2><big>Hinweis!</big><br><br>
<?
	Output(-1, 351,
"         Sie haben das Start&minus; bzw. Endedatum des Tasks
         ge&auml;ndert. Diesem Task sind jedoch bereits Mitarbeiter
         zugeordnet, deren Perioden nun (teilweise) au&szlig;erhalb des
         Zeitraums des Tasks fallen w&uuml;rden.<br><br>
         Wenn Sie folgende Frage mit <b>JA</b> beantworten, werden jene
         Perioden geloescht, die au&szlig;erhalb des Taskzeitraums liegen!<br><br>
         Wollen Sie die Perioden der zugeordneten Mitarbeiter die au&szlig;erhalb des
         Taskzeitraums liegen wirklich loeschen?");
?>
      </td>
   </tr>
   <tr>
<?
	echo "<td align=\"center\">";
	Button("Ja", "obsolete");
	echo "</td><td align=\"center\">";
	ButtonLink("Abbrechen", "plan.php", "editplan=$ta_plnum&menu=$menu&headline=$headline");
	echo "</td>";
?>
   </tr>
</table>
</center>
</form>
<?php
}

function SaveTask($doit=false) {
	global $phase;
	$ta_num = $_REQUEST['ta_num'];
	$ta_plnum = $_REQUEST['ta_plnum'];
	$ta_id = $_REQUEST['ta_id'];
	$ta_level = $_REQUEST['ta_level'];
	$ta_name = $_REQUEST['ta_name'];
	$ta_color = $_REQUEST['ta_color'];
	$ta_meeting = $_REQUEST['ta_meeting'];
	$start = $_REQUEST['start'];
	$end = $_REQUEST['ende'];
	$ta_duration = $_REQUEST['ta_duration'];
	$ta_complete = $_REQUEST['ta_complete'];
	$ta_priority = $_REQUEST['ta_priority'];
	$ta_depend = $_REQUEST['ta_depend'];
	$ta_deptype = $_REQUEST['ta_deptype'];
	$ta_notiz = $_REQUEST['ta_notiz'];
	$ta_risiko = $_REQUEST['ta_risiko'];
	$folder = $_REQUEST['folder'];

	if ($phase)
	   $ta_phase = $_REQUEST['ta_phase'];
	else
	   $ta_phase = 0;

	# Plausibilitaetspruefungen
	$err = 0;

	if (!isset($ta_plnum) || $ta_plnum < 1) {
	   Error(GetMessage(-1, 341, "Interner Fehler: Plannummer fehlt!"));
	   $err = 1;
	}

	if (!isset($ta_id) || $ta_id < 1) {
	   Error(GetMessage(-1, 342, "Interner Fehler: Keine oder ung&uuml;ltige ID-Nummer!"));
	   $err = 1;
	}

	if (strlen($ta_name) < 1) {
	   Error(GetMessage(-1, 343, "Ein Task muss einen Namen haben!"));
	   $err = 1;
	}

	if (strlen($ta_color) != 6) {
	   Error(GetMessage(-1, 344, "Ung&uuml;ltiger Farbcode! Standard (hellgelb) wurde gesetzt!"));
	   $ta_color = "ffffcc";
	}

	if (!isset($ta_meeting)) {
	   $ta_meeting = 0;
	}

	if (!isset($ta_risiko) || $ta_meeting)
	   $ta_risiko = 0;

	if (strlen($start) < 8 || str_wordcount($start) != 3) {
	   Error(GetMessage(-1, 345, "Ung&uuml;ltiges Startdatum! (%s)", $start));
	   $err = 1;
	}

	if (!$ta_meeting && (strlen($end) < 8 || str_wordcount($end) != 3)) {
	   Error(GetMessage(-1, 346, "Ung&uuml;ltiges Endedatum! (%s)", $end));
	   $err = 1;
	}

	$db = OpenDB();
	# Datum des letzten Teilprojektabschlusses ermitteln.
	$query = "select pl_prnum from plan where pl_num = $ta_plnum";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$pl_prnum = $data[0];
	
	$query = "select ab_datum from abschluss where ab_prnum = $pl_prnum ";
	$query .= "order by ab_Datum desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	if (numrowsDB($result) > 0) {
	   $data = fetchDB($result, 0);
	   $ab_datum = $data[0];
	} else
	   $ab_datum = 0;

	# Pruefen ob die eingegebenen Datum korrekt sind.
	$dt = explode(".", $start);
	$ta_start = gmmktime(0, 0, 0, $dt[1], $dt[0], $dt[2]);

//	if (isset($ta_num) && $ta_num > 0 && $ta_start <= $ab_datum) {
//	   Error(GetMessage($db, 349, "Das Startdatum darf nicht vor dem Datum des letzten Teilprojektabschlu&szlig; sein!"));
//	   $err = 1;
//	}

	if (!$ta_meeting) {
	   $dt = explode(".", $end);
	   $ta_end = gmmktime(0, 0, 0, $dt[1], $dt[0], $dt[2]);
	} else
	   $ta_end = $ta_start;

	if ($ta_meeting == 0 && $ta_start > $ta_end) {
	   Error(GetMessage(-1, 347, "Das Startdatum darf nicht gr&ouml;&szlig;er als das Endedatum sein!"));
	   $err = 1;
	}

//	if (!$err && isset($ta_num) && $ta_num > 0 && $ta_end <= $ab_datum) {
//	   Error(GetMessage($db, 350, "Das Endedatum darf nicht vor dem Datum des letzten Teilprojektabschlu&szlig; sein!"));
//	   $err = 1;
//	}

	if (!isset($ta_depend) || strlen($ta_depend) == 0) {
	   $ta_depend = 0;
	}

	if ($ta_complete > 100) {
	   $ta_complete = 100;
	}

	# Wenn der vorhergehende Task, sofern einer existiert, ein Meilenstein
	# ist, dann darf der Level des folgenden Tasks nicht hoeher sein.
	$query = "select ta_level, ta_meeting from task where ";
	$query .= "ta_plnum = $ta_plnum and ta_id < $ta_id order by ta_id desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	if (numrowsDB($result) > 0) {
	   $data = fetchDB($result, 0);
	   $level = $data[0];
	   $meeting = $data[1];

	   if ($meeting && !$ta_meeting && $ta_level > $level) {
	      Error(GetMessage($db, 348, "Der \"Level\" ist au&szlig;erhalb des g&uuml;ltigen Bereichs!"));
	      $err = 1;
	   }
	}

	if ($ta_level < 1 || $ta_level > 99) {
	   Error(GetMessage($db, 348, "Der \"Level\" ist au&szlig;erhalb des g&uuml;ltigen Bereichs!"));
	   $err = 1;
	}

	if ($err == 1) {
	   closeDB($db);
	   return false;
	}

	# Umwandlungen
	$ta_color = hexdec($ta_color);

	if (!$ta_meeting)
	   $ta_duration = ($ta_end - $ta_start) / 86400;
	else
	   $ta_duration = 0;

	# Aendern wir einen bestehenden Datensatz, oder speichern wir einen
	# neuen?
	if (isset($ta_num) && $ta_num > 0) {		// neuer Datensatz?
	   $query = "select ta_start, ta_duration from task where ta_num = $ta_num";

	   if (!($result = QueryDB($db, $query))) {
	      closeDB($db);
	      return false;
	   }

	   $numrows = numrowsDB($result);

	   # Pruefen ob das eventuell geaenderte Startdatum nicht in einer
	   # zukuenftigen Periode liegt und bereits zugewiesene Mitarbeiter
	   # in der Luft haengen wuerden. Ist das der Fall, muss der User
	   # darauf hingewiesen werden und, wenn er es will, die nicht mehr
	   # zugeordneten Mitarbeiter geloescht werden.
	   #
	   if ($numrows == 1 && !$doit) {
	      $data = fetchDB($result, 0);
	      $old_tastart = $data[0];
	      $old_taduration = $data[1];
	      $oend = $old_tastart + ($old_taduration * 86400);
	      $dend = $ta_start + ($ta_duration * 86400);

	      # Prufen, ob das Start- oder Endedatum geaendert wurde und wenn
	      # ja, dann duerfen die neuen Datum nicht juenger als das letzte
	      # Datum des Teilprojektabschluss sein.

	      if (!$folder && (($old_tastart != $ta_start && $ta_start <= $ab_datum) ||
		  ($old_taduration != $ta_duration && $dend <= $ab_datum))) {
		 Error(GetMessage($db, 352, "Das Startdatum und/oder das Endedatum darf nicht vor dem Datum des letzten Teilabschluss sein!"));
		 closeDB($db);
		 return false;
	      }

	      # Pruefen, ob die neuen Start- oder Endedatum keine in der Luft
	      # haengenden Planwerte hinterlassen.
	      if (PerDateComp($ta_start, $old_tastart) < 0 ||
	          PerDateComp($oend, $dend) < 0) {
		 $query = "select al_num, al_pstart from allocation where ";
		 $query .= "al_task = $ta_num and (al_pstart < $ta_start or ";
		 $query .= "al_pstart > $dend)";

		 if (!($result = QueryDB($db, $query))) {
		    closeDB($db);
		    return false;
		 }

		 $rows = numrowsDB($result);

		 if ($rows > 0) {	// Gibt es MA unterhalb von ta_start?
		    AskObsoleteMA();
		    closeDB($db);
		    require('footer.inc');
		    exit();
		 }
	      }
	   } /* else
	      $numrows = 0;
*/
	   # Gibt es den Datensatz bereits, dann aendern wir ihn.
	   if ($numrows == 1) {
	      if ($doit) {
	         $dend = $ta_start + ($ta_duration * 86400);
	         QueryDB($db, "begin");
	         $query = "delete from allocation where al_task = $ta_num and ";
	         $query .= "(al_pstart < $ta_start or al_pstart > $dend)";

	         if (!QueryDB($db, $query)) {
		    closeDB($db);
		    return false;
	         }
	      }

	      $query = "update task set ta_name = '$ta_name', ta_color = '$ta_color',";
	      $query .= "ta_meeting = $ta_meeting, ta_start = $ta_start,";
	      $query .= "ta_duration = $ta_duration, ta_complete = $ta_complete,";
	      $query .= "ta_priority = $ta_priority, ta_level = $ta_level,";
	      $query .= "ta_depend = $ta_depend, ta_deptype = $ta_deptype,";

	      if ($phase == 1)
	         $query .= "ta_plnum = $ta_plnum, ta_id = $ta_id, ta_phase = $ta_phase,";
	      else
	         $query .= "ta_plnum = $ta_plnum, ta_id = $ta_id,";

	      $query .= "ta_notiz = '$ta_notiz', ta_risiko = $ta_risiko where ta_num = $ta_num";

	      if (!QueryDB($db, $query)) {
		 if ($doit)
		    QueryDB($db, "rollback");

		 closeDB($db);
		 return false;
	      }

	      if ($doit)
	         QueryDB($db, "commit");

	      closeDB($db);
	      return true;
	   }
	}

	# Der Datensatz existiert nicht und deshalb fuegen wir ihn ein. Es
	# muss jedoch geprueft werden, ob die ID bereits existiert. Existiert
	# sie, muessen alle IDs >= #ta_id um 1 erhoeht werden und der
	# Datensatz anschliessend eingefuegt werden.
	$query = "select ta_id from task where ta_plnum = $ta_plnum and ta_id = $ta_id";
	$result = QueryDB($db, $query);
	$numrows = numrowsDB($result);

	if ($numrows == 1) {
	   # Alle IDs um 1 nach hinten schieben!
	   $query = "select ta_num, ta_id from task where ta_plnum = $ta_plnum and ta_id >= $ta_id order by ta_id desc";
	   $result = QueryDB($db, $query);
	   $numrows = numrowsDB($result);
	   $row = 0;
	   $db2 = OpenDB();

	   while ($row < $numrows) {
	      $data = fetchDB($result, $row);
	      $num = $data[0];
	      $id = $data[1] + 1;
	      $query = "update task set ta_id = $id where ta_num = $num";

	      if (!TQueryDB($db2, $query)) {
	         Error("SQL-Error: $query");
		 closeDB($db);
		 closeDB($db2);
		 return false;
	      }

	      $row++;
	   }

	   closeDB($db2);
	}

	# Nun wird der neue Datensatz tatsaechlich geschrieben.
	$query = "select co_task from counter";
	$result = QueryDB($db, $query);
	$data = fetchDB($result, 0);
	$ta_num = $data[0] + 1;
	$ta_hash = md5($ta_num);

	QueryDB($db, "begin");
	$query = "insert into task (ta_num, ta_plnum, ta_id, ta_depend,";
	$query .= "ta_deptype, ta_name, ta_color, ta_shape, ta_meeting,";
	$query .= "ta_start, ta_duration, ta_complete, ta_fixed_start,";
	$query .= "ta_priority, ta_level, ta_phase, ta_notiz, ta_hash, ta_risiko) values (";
	$query .= "$ta_num, $ta_plnum, $ta_id, $ta_depend, $ta_deptype,";
	$query .= "'$ta_name', $ta_color, '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0',";
	$query .= "$ta_meeting, $ta_start, $ta_duration, $ta_complete,";

	if ($phase == 1)
	   $query .= "0, $ta_priority, $ta_level, $ta_phase, '$ta_notiz', '$ta_hash', $ta_risiko)";
	else
	   $query .= "0, $ta_priority, $ta_level, 0, '$ta_notiz', '$ta_hash', $ta_risiko)";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   Error("SQL-Error: $query");
	   closeDB($db);
	   return false;
	}

	$query = "update counter set co_task = $ta_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   Error("SQL-Error: $query");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(300, "plan.php: SaveTask: task=$ta_num", $db);
	closeDB($db);
	return true;
}

function AddMiAdd() {
	global $periode;
	global $phase;
	global $role;

	$al_task = $_REQUEST['al_task'];
	$al_ressource = $_REQUEST['al_ressource'];
	$al_hours = $_REQUEST['al_hours'];

	if ($role)
	   $al_role = $_REQUEST['al_role'];

	$al_pstart = $_REQUEST['al_pstart'];

	if ($phase)
	   $al_phase = $_REQUEST['al_phase'];
	else
	   $al_phase = 0;

	$al_hours = str_replace(",", ".", $al_hours);

	if ($al_hours <= 0 || $al_hours > 99.999) {
	   Error("Error: Die Projekttage (PT) m&uuml;ssen im Bereich 1 bis 99,999 sein!<br>\n");
	   return false;
	}

	$db = OpenDB();
	$query = "select co_allocation from counter";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$co_allocation = $data[0] + 1;
	$mon = gmdate("n", $al_pstart);
	$year = gmdate("Y", $al_pstart);

	switch ($periode) {
	   case 1: $al_pduration = 364; break;
	   case 2: $al_pduration = 91; break;
	   case 3: $al_pduration = daysinmonth($mon, $year); break;
	   case 4: $al_pduration = 1; break;
	   default: $al_pduration = daysinmonth($mon, $year); break;
	}

	QueryDB($db, "begin");

	if (!$phase)
	   $al_phase = 0;

	$query = "insert into allocation (al_num, al_task, al_ressource,";

	if ($role)
	   $query .= "al_hours, al_phase, al_role, al_pstart, al_pduration) ";
	else
	   $query .= "al_hours, al_phase, al_pstart, al_pduration) ";

	$query .= "values ($co_allocation, $al_task,";

	if ($role)
	   $query .= "$al_ressource, $al_hours, $al_phase, $al_role,";
	else
	   $query .= "$al_ressource, $al_hours, $al_phase, ";

	$query .= "$al_pstart, $al_pduration)";
	$result = QueryDB($db, $query);

	if (!$result) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	$query = "update counter set co_allocation = $co_allocation";
	$result = QueryDB($db, $query);

	if (!$result) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(202, "plan.php: AddMiAdd: task=$al_task; ressource=$al_ressource", $db);
	closeDB($db);
	return true;
}

function AddMiDel($al_num) {
	global $unum;
	global $rstufe;

	$db = OpenDB();
	$query = "delete from allocation where al_num = $al_num";
	$result = TQueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	Journal(105, "plan.php: AddMiDel: al_num=$al_num", $db);
	closeDB($db);
	return true;
}

# Folgende Funktion ermittelt die Summe aller Planwerte eines bestimmten
# Mitarbeiters in einer bestimmten Periode.
#
function GetRessource($db, $mi_num, $periode) {
	$mon = gmdate("n", $periode);
	$year = gmdate("Y", $periode);
	$per_start = gmmktime(0, 0, 0, $mon, 1, $year);
	$per_end = gmmktime(0, 0, 0, $mon, daysinmonth($mon, $year), $year);
	$query = "select sum(al_hours) from allocation, task, plan where ";
	$query .= "ta_num = al_task and pl_num = ta_plnum and pl_status in (2,4) and ";
	$query .= "al_ressource = $mi_num and al_pstart between $per_start and $per_end";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	$data = fetchDB($result, 0);
	return $data[0];
}

function PrintMa($db, $dstart, $dend, $al_task, $color, $pl_num, $ressource, $lock=false) {
	global $periode;
	global $einheit;
	global $menu;
	global $phase;
	global $role;
	global $verrmodul;
	global $stdwhg;
	global $ab_datum;
	global $rstufe;

	$nav = "pl_num=$pl_num&al_task=$al_task&menu=$menu&headline=20";
	$query = "select am_num, am_task, am_ressource, am_hours, am_pstart,";
	$query .= "am_pduration, am_role, am_krnum, am_nname, am_vname, am_phase ";
	$query .= "from allocmi where am_task = $al_task order by ";
	$query .= "am_nname, am_vname, am_pstart";
	$erg = QueryDB($db, $query);

	if (!$erg)
	   return 0;

	$erganz = numrowsDB($erg);
	$ergrow = 0;
	$oressource = 0;
	$dt = 0;
	$sum = 0;
	$total = 0;
	$brutto = 0;

	while ($ergrow < $erganz) {
	   $data = fetchDB($erg, $ergrow);
	   $am_num = $data[0];
	   $am_task = $data[1];
	   $am_ressource = $data[2];
	   $am_hours = $data[3];
	   $am_pstart = $data[4];
	   $am_pduration = $data[5];
	   $am_role = $data[6];
	   $am_krnum = $data[7];
	   $am_nname = $data[8];
	   $am_vname = $data[9];
	   $am_phase = $data[10];

	   # Wenn das Verrechnungsmodul aktiv ist, benoetigen wir den
	   # Tagsatz des Mitarbeiters.
	   if ($oressource != $am_ressource) {
	      if ($oressource != 0) {
	         $ed = GetEDate($einheit, $ta_start, $ta_duration);

		 if ($dt < $ed) {
		    while (PerDateComp($dt, $ed) >= 0) {
		       if ($oressource == $ressource) {
			  $res_hours = GetRessource($db, $ressource, $dt);
			  $pts = GetPT($dt);
			  $mon = gmdate("n", $dt);
			  $year = gmdate("Y", $dt);
			  $nm = "dt_0_" . (string)$mon;
			  $nm .= "_" . (string)$year;

			  if ($dt > $ab_datum || $rstufe == 1) {
			     echo "<td class=\"sel\"><input type=\"text\" name=\"$nm\" size=6 maxlength=6 ";
			     echo "onChange=\"javascript:CheckOverload(this, $res_hours, $pts)\"></td>\n";
			  } else {
			     echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
			  }
		       }
		       else
			  echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";

		       $dt = IncDate($periode, $dt);
		    }
		 }

		 while (PerDateComp($dt, $dend) >= 0) {
		    $dt = IncDate($periode, $dt);
		    echo "<td class=\"sel\">&nbsp;</td>";
		 }

		 printf ("<td class=\"selnum\"><b>%s</b></td>\n", FormatNum($sum, 3));
		 $total += $sum;

		 if ($verrmodul) {
		    echo "<td class=\"sel\">&nbsp;</td>";
		    printf ("<td class=\"selnum\">%s</td>", FormatNum($brutto, 2));
		    echo "<td class=\"sel\">&nbsp;</td>";
		    echo "<td class=\"sel\">&nbsp;</td>";
	         }

		 $sum = 0;
		 $brutto = 0;
		 echo "</tr>\n";
	      }

	      # Starrer Zeilenbegin ...
	      echo "<tr>\n";
	      # Button
	      echo "<td class=\"selakt\">";

	      if (!$lock && $am_ressource == $ressource) {
		 echo "<a name=\"edit\"></a>\n";		# Einsprungpunkt
		 echo "<form name=\"PrintMa\" action=\"plan.php\" method=\"post\">\n";
		 echo "<input type=\"hidden\" name=\"pl_num\" value=\"$pl_num\">\n";
		 echo "<input type=\"hidden\" name=\"ressource\" value=\"$am_ressource\">\n";
		 echo "<input type=\"hidden\" name=\"ta_num\" value=\"$al_task\">\n";
		 echo "<input type=\"hidden\" name=\"al_phase\" value=\"$am_phase\">\n";
		 echo "<input type=\"hidden\" name=\"al_role\" value=\"$am_krnum\">\n";
		 echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
		 echo "<input type=\"hidden\" name=\"headline\" value=\"20\">\n";
		 echo "<input type=\"hidden\" name=\"func\" value=\"SaveUpMa\">\n";
/*		 echo "<button type=\"submit\" name=\"submit\">";
		 echo "<img src=\"image/new.png\" border=0 alt=\"Speichern\">";
		 echo "</button>\n";
*/
		 ButtonImage("filesave.png", "PrintMa", "Speichern");
	      } else if (!$lock) {
	         echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php',";
		 echo "'ressource=$am_ressource&func=UpdateMa&$nav#edit')\">";
		 echo "<img src=\"image/edit.png\" border=0 alt=\"Update\"></a>";
	         echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php',";
		 echo "'ta_num=$am_task&ressource=$am_ressource&func=AskDeleteMa&$nav')\">";
		 echo "<img src=\"image/editdelete.png\" border=0 alt=\"Loeschen\"></a>";
	      } else
	         echo "&nbsp;";

	      echo "</td>\n";
	      # Nummerierung
              echo "<td class=\"sel\">&nbsp;</td>\n";
	      # Ressource
	      echo "<td colspan=2 class=\"sel\" width=\"20%\"> </td>\n";
	      echo "<td class=\"sel\"><i>$am_nname $am_vname";
	      
	      if ($role)
	         echo ", $am_role";

	      echo "</i></td>\n";
	      # Tasklaenge mit Einheit
	      echo "<td colspan=3 class=\"sel\">&nbsp;</td>\n";
	      # Mitarbeiterrolle

#	      if ($role)
#	         echo "<td class=\"sel\">$am_role</td>\n";

	      # Zellen bis zum Taskanfang schreiben
	      $query = "select ta_start, ta_duration from task where ta_num = $am_task";

	      if (!($res = QueryDB($db, $query))) {
		 Error(GetMessage($db, 339, "Keinen dazupassenden Task gefunden!"));
		 return 0;
	      }

	      $data = fetchDB($res, 0);
	      $ta_start = $data[0];
	      $ta_duration = $data[1];
	      $dt = $dstart;

	      while (PerDateComp($dt, $ta_start) > 0) {
		 $dt = IncDate($periode, $dt);
		 echo "<td class=\"sel\">&nbsp;</td>";
	      }

	      # Falls wir Eingabezeilen benoetigen die vor dem ersten
	      # gespeicherten Task beginnen, schreiben wir diese hier.
	      if ($ressource == $am_ressource && $ta_start < $am_pstart) {
		 while (PerDateComp($dt, $am_pstart) > 0) {
		    $res_hours = GetRessource($db, $ressource, $dt);
		    $pts = GetPT($dt);
		    $mon = gmdate("n", $dt);
		    $year = gmdate("Y", $dt);
		    $nm = "dt_0_" . (string)$mon;
		    $nm .= "_" . (string)$year;

		    if ($dt > $ab_datum || $rstufe == 1) {
		       echo "<td class=\"sel\"><input type=\"text\" name=\"$nm\" size=6 maxlength=6 ";
		       echo "onChange=\"javascript:CheckOverload(this, $res_hours, $pts)\"></td>\n";
		    } else
		       echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";

		    $dt = IncDate($periode, $dt);
		 }
	      }

	      $oressource = $am_ressource;
	   }

	   # Rest der Zeile schreiben
	   $PerStart = GetPeriode($am_pstart);
	   $pyear = gmdate("Y", $am_pstart);
	   $PerAkt = GetPeriode($dt);
	   $tyear = gmdate("Y", $dt);

	   # Wenn das Verrechnungsmodul aktiv ist, benoetigen wir den
	   # Tagsatz des Mitarbeiters zum aktuellen Datum.
	   if ($verrmodul) {
	      $query = "select tg_amount, tg_whg from tagsatz where ";
	      $query .= "tg_minum = $am_ressource and tg_valid_from <= to_date('" . gmdate("d.m.Y", $dt) . "','DD.MM.YYYY') and ";
	      $query .= "(tg_valid_to >= to_date('" . gmdate("d.m.Y", GetUltimo($dt)) . "','DD.MM.YYYY') or tg_valid_to is NULL) ";
	      $query .= "order by tg_valid_from, tg_valid_to";

	      if (!($resver = QueryDB($db, $query)))
	         return 0;

	      if (numrowsDB($resver) > 0) {
	         $data = fetchDB($resver, 0);
		 $tg_amount = $data[0];
		 $tg_whg = $data[1];
	      } else {
	         $tg_amount = 0.0;
		 $tg_whg = $stdwhg;
	      }
	   }

	   if ($ressource == $am_ressource) {
	      $tm = gmdate("j.n.Y", $dt);
	      $ad = explode(".", $tm);
	      $res_hours = GetRessource($db, $ressource, $dt);
	      $pts = GetPT($dt);

	      if ($PerStart == $PerAkt) {
		 $nm = "dt_" . (string)$am_num . "_" . (string)$ad[1];
		 $nm .= "_" . (string)$ad[2];

		 if ($dt > $ab_datum || $rstufe == 1) {
		    printf("<td class=\"sel\"><input type=\"text\" name=\"$nm\" value=\"%s\" size=6 maxlength=6 ", FormatNum($am_hours, 3));
		    echo "onChange=\"javascript:CheckOverload(this, $res_hours, $pts)\"></td>\n";
		 } else {
		    echo "<td style=\"background-color: #$color; border: 1px solid black; text-align: right;\">";
		    echo FormatNum($am_hours, 3) . "</td>\n";
		 }

		 $sum += $am_hours;
		 $brutto += $am_hours * $tg_amount;
		 $ergrow++;
	      } else {
		 $nm = "dt_0_" . (string)$ad[1];
		 $nm .= "_" . (string)$ad[2];

		 if ($dt > $ab_datum || $rstufe == 1) {
		    echo "<td class=\"sel\"><input type=\"text\" name=\"$nm\" size=6 maxlength=6 ";
		    echo "onChange=\"javascript:CheckOverload(this, $res_hours, $pts)\"></td>\n";
		 } else
		    echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
	      }
	   } else {
	      if ($PerStart == $PerAkt && $pyear == $tyear) {
		 printf ("<td style=\"background-color: #$color; border: 1px solid black; text-align:right;\">%s</td>\n", FormatNum($am_hours, 3));
		 $sum += $am_hours;
		 $brutto += $am_hours * $tg_amount;
		 $ergrow++;
	      } else
		 echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
	   }

	   $dt = IncDate($periode, $dt);
	}

	if ($erganz > 0) {
	   $ed = GetEDate($einheit, $ta_start, $ta_duration);

	   if ($dt < $ed) {
	      while (PerDateComp($dt, $ed) >= 0) {
		 if ($oressource == $ressource) {
		    $res_hours = GetRessource($db, $am_ressource, $dt);
		    $pts = GetPT($dt);
		    $mon = gmdate("n", $dt);
		    $year = gmdate("Y", $dt);
		    $nm = "dt_0_" . (string)$mon;
		    $nm .= "_" . (string)$year;

		    if ($dt > $ab_datum || $rstufe == 1) {
		       echo "<td class=\"sel\"><input type=\"text\" name=\"$nm\" size=6 maxlength=6 \n";
		       echo "onChange=\"javascript:CheckOverload(this, $res_hours, $pts)\"></td>\n";
		    } else
		       echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
		 }
		 else
		    echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";

	         $dt = IncDate($periode, $dt);
	      }
	   }

	   while (PerDateComp($dt, $dend) >= 0) {
	      $dt = IncDate($periode, $dt);
	      echo "<td class=\"sel\">&nbsp;</td>";
	   }

	   printf ("<td class=\"selnum\"><b>%s</b></td>\n", FormatNum($sum, 3));
	   $total += $sum;

	   if ($verrmodul) {
	      echo "<td class=\"sel\">&nbsp;</td>";
	      printf ("<td class=\"selnum\">%s</td>", FormatNum($brutto, 2));
	      echo "<td class=\"sel\">&nbsp;</td>";
	      echo "<td class=\"sel\">&nbsp;</td>";
	   }

	   echo "</tr>\n";

	   if ($am_ressource == $ressource)
	      echo "</form>\n";
	}

	return $total;
}

# Liefert den Level des Tasks vor dem angegebenen. Existiert kein Task
# davor, wird -1 zurueckgegeben.
#
function GetPreviousLevel($db, $ta_num) {
	$query = "select ta_id, ta_plnum from task where ta_num = $ta_num";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	$data = fetchDB($result, 0);
	$ta_id = $data[0];
	$ta_plnum = $data[1];
	$query = "select ta_level from task where ta_plnum = $ta_plnum ";
	$query .= "and ta_num != $ta_num and ta_id < $ta_id ";
	$query .= "order by ta_id desc";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	if (numrowsDB($result) <= 0)
	   return -1;

	$data = fetchDB($result, 0);
	return $data[0];
}

# Liefert den Level des Tasks nach dem angegebenen. Existiert kein Task
# danach, wird -1 zurueckgegeben.
#
function GetNextLevel($db, $ta_num) {
	$query = "select ta_id, ta_plnum from task where ta_num = $ta_num";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	$data = fetchDB($result, 0);
	$ta_id = $data[0];
	$ta_plnum = $data[1];
	$query = "select ta_level from task where ta_plnum = $ta_plnum ";
	$query .= "and ta_num != $ta_num and ta_id > $ta_id ";
	$query .= "order by ta_id";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	if (numrowsDB($result) <= 0)
	   return -1;

	$data = fetchDB($result, 0);
	return $data[0];
}

# Folgende Funktion liefert den vorhergehenden, oder den nachfolgenden Task,
# mit welchem getauscht werden kann. Es handelt sich also um einen Task
# des selben Levels.
#
function GetReplaceTask($db, $ta_num, $dir) {
	$query = "select ta_id, ta_plnum, ta_level from task where ta_num = $ta_num";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	$data = fetchDB($result, 0);
	$ta_id = $data[0];
	$ta_plnum = $data[1];
	$ta_level = $data[2];
	$query = "select ta_num from task where ta_plnum = $ta_plnum ";
	$query .= "and ta_num != $ta_num and ta_level = $ta_level and ta_id ";

	if ($dir > 0)		// 0 = Rueckwaerts, 1 = Vorwaerts
	   $query .= "> ";
	else
	   $query .= "< ";

	$query .= "$ta_id order by ta_id";

	if ($dir == 0)
	   $query .= " desc";

	if (!($result = QueryDB($db, $query)))
	   return -1;

	if (numrowsDB($result) <= 0)
	   return -1;

	$data = fetchDB($result, 0);
	return $data[0];
}

# Die Funktion tauscht die Reihen folge eines Tasks, so das ein Task nach
# oben oder unten verschoben werden kann.
#
function MoveTask($ta_num, $dir) {
	$db = OpenDB();
	$query = "select ta_id, ta_plnum, ta_level from task where ta_num = $ta_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$ta_id = $data[0];
	$ta_plnum = $data[1];
	$ta_level = $data[2];
	$query = "select ta_num, ta_id from task where ta_plnum = $ta_plnum and ";
	$query .= "ta_level = $ta_level and ";

	if ($dir < 0) {
	   $query .= "ta_num != $ta_num and ta_id < $ta_id ";
	   $query .= "order by ta_id desc";
	} else {
	   $query .= "ta_num != $ta_num and ta_id > $ta_id ";
	   $query .= "order by ta_id";
	}

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return false;
	}

	if (numrowsDB($result) <= 0) {
	   Error("Interner Fehler: In der gew&auml;hlten Richtung existiert kein geeigneter Task!");
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$ta_num1 = $data[0];
	$ta_id1 = $data[1];

	# Tauschen der Tasks
	QueryDB($db, "begin");
	$query = "update task set ta_id = -1 where ta_num = $ta_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	$query = "update task set ta_id = $ta_id where ta_num = $ta_num1";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	$query = "update task set ta_id = $ta_id1 where ta_num = $ta_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	closeDB($db);
	return true;
}

# Folgenden Funktionen erlauben die Erfassung von Plaenen, wobei die
# einzelnen Perioden dargestellt werden, welche mit individuellen Zeiten
# gefuellt werden koennen.
# Es wird immer der Zeitraum vom Start des Projekts bis zu seinem Ende
# dargestellt. Bei sehr langen Projekten oder sehr kleinen Perioden, kann
# die Tabelle durchaus sehr breit werden.
#
function PlanPeriode($pl_num, $ta_num, $ressource, $new=false, $lock=false) {
	global $rstufe;
	global $unum;
	global $periode;
	global $verteil;
	global $einheit;
	global $menu;
	global $phase;
	global $dtformatshort;
	global $role;
	global $pmlight;
	global $stdwhg;
	global $verrmodul;
	global $ab_datum;

	if ($pl_num <= 0) {
	   Error(GetMessage(-1, 327, "Interner Fehler: Es wurde keine Plannummer an \"PlanPeriode\" &uuml;bergeben!"));
	   return;
	}

	if ($rstufe != 1 && $rstufe != 2) {
	   Error(GetMessage(-1, 50, "Berechtigungsfehler!"));
	   return;
	}

	if (!isset($ta_num))
	   $ta_num = 0;

	if (!isset($ressource))
	   $ressource = 0;
	else if ($ressource > 0)
	   $tanum = $ta_num;

	if ($lock && $new)
	   $new = false;

	$db = OpenDB();
	$query = "select pr_name, pl_prnum, mi_nname, mi_vname from ";
	$query .= "plan, project, mitarbeiter where pl_num = $pl_num and ";
	$query .= "pr_num = pl_prnum and mi_num = pr_pl";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$pr_name = $data[0];
	$pl_prnum = $data[1];
	$mi_nname = $data[2];
	$mi_vname = $data[3];

	# Ermitteln des letzten Abschlussdatums fuer das aktuelle Projekt
	$query = "select ab_datum from abschluss where ";
	$query .= "ab_prnum = $pl_prnum ";
	$query .= "order by ab_datum desc";

	if (!($resab = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	if (numrowsDB($resab) > 0) {
	   $data = fetchDB($resab, 0);
	   $ab_datum = $data[0];
	} else
	   $ab_datum = 0;

	# Zeichnen der fixen Kopfspalten.
        if ($new) {
           $id = $_REQUEST['ta_num'];

           if (!isset($id))
              $id = 0;
?>
<form name="plan" action="plan.php" method="post">
<input type="hidden" name="menu" value="<? echo "$menu"; ?>">
<input type="hidden" name="headline" value="20">
<input type="hidden" name="pl_num" value="<? echo "$pl_num"; ?>">
<?php
        }

	# Eingabezeile fuer den Plankommentar anzeigen.
	$query = "select pl_comment from plan where pl_num = $pl_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$pl_comment = $data[0];

	if (!$lock && !$new) {
	   echo "<form name=\"plcomment\" aktion=\"plan.php\" method=\"post\">\n";
	   echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
	   echo "<input type=\"hidden\" name=\"headline\" value=\"20\">\n";
	   echo "<input type=\"hidden\" name=\"pl_num\" value=\"$pl_num\">\n";
	   echo "<input type=\"hidden\" name=\"func\" value=\"COMMENT\">\n";
	}

	echo "<table class=\"input\">\n";
	echo "<tr><td>" . GetMessage($db, 1, "Projekt:") . "</td><td>$pl_prnum $pr_name</td></tr>\n";
	echo "<tr><td>" . GetMessage($db, 328, "Projektleiter:") . "</td><td>$mi_nname $mi_vname</td></tr>\n";
	echo "<tr><td>" . GetMessage($db, 19, "Kommentar:") . "</td>\n";

	if (!$lock && !$new) {
	   if ($pmlight)
	      $class = " class=\"inputmust\"";

	   echo "<td><input type=\"text\"$class name=\"pl_comment\" ";
	   echo "value=\"" . htmlentities($pl_comment) . "\" onChange=\"javascript:document.plcomment.submit()\" ";

	   if ($pmlight)
	      echo "size=\"30\" maxlength=\"30\"></td>\n";
	   else
	      echo "size=\"80\" maxlength=\"255\"></td>\n";
	} else {
	   echo "<td>$pl_comment</td>\n";
	}

	echo "</tr></table>\n";

	if (!$lock && !$new)
	   echo "</form>\n";
	
	$nav = "pl_num=$pl_num&menu=$menu&headline=20";
?>
<table class="sel">
   <tr>
      <th class="sel" rowspan=2>Akt</th>
      <th class="sel" rowspan=2>Num.</th>
      <th class="sel" colspan=3 rowspan=2>
         <table border=0 width="100%"><tr><td align="center" colspan=2><? Output($db, 333, "Taskname"); ?></td></tr>
	    <tr><td>&nbsp;</td><td align="right"><? Output($db, 329, "Ressource"); ?></td></tr>
	 </table>
      </th>
      <th class="sel" rowspan=2 colspan=3>
         <table border=0 width="100%"><tr><td align="center" colspan=3><? Output($db, 334, "Arbeit"); ?></td></tr>
	    <td align="center"><? Output($db, 330, "Dauer"); ?></td>
	    <td align="center"><? Output($db, 331, "Start"); ?></td>
	    <td align="center"><? Output($db, 332, "Ende"); ?></td></tr>
	 </table>
      </th>
<?
#	if ($role)
#	   echo "      <th class=\"sel\" rowspan=2>" . GetMessage($db, 335, "Rolle") . "</th>\n";

	# Ermitteln des Projektstarts um den Tabellenkopf fertig zu schreiben.
	$query = "select ta_start, ta_duration, ta_meeting from task where ";
	$query .= "ta_plnum = $pl_num order by ta_start";
	$resta = QueryDB($db, $query);

	if (!$resta) {
	   closeDB($db);
	   return;
	}

	$numrows = numrowsDB($resta);
	$row = 0;
	$fdate = 0;
	$ldate = 0;

	while ($row < $numrows) {
	   $data = fetchDB($resta, $row);
	   $ta_start = $data[0];
	   $ta_duration = $data[1];
	   $ta_meeting = $data[2];

	   if ($row == 0)
	      $fdate = $ta_start;

	   if ($ta_meeting)
	      $ed = $ta_start;
           else
	      $ed = GetEDate($einheit, $ta_start, $ta_duration);

	   if ($ed > $ldate)
	      $ldate = $ed;

	   $row++;
	}

	# Erstellen des restlichen Tabellenkopfs ...
	$tm = gmdate("j.n.Y", $fdate);
	$dt = explode(".", $tm);
	$smon = $dt[1];
	$syear = $dt[2];
	$dt = $fdate;
	$cols = 0;
	$tbcols = 1;
	$oyear = $syear;

	while (PerDateComp($dt, $ldate) > 0) {
	   $syear = gmdate("Y", $dt);

	   if ($oyear != $syear) {
	      if ($cols <= 1)
	         echo "<th class=\"sel\">$oyear</th>\n";
	      else
	         echo "<th class=\"sel\" colspan=$cols>$oyear</th>\n";

	      $oyear = $syear;
	      $cols = 0;
	   }

	   $cols++;
	   $tbcols++;
	   $dt = IncDate($periode, $dt);
	}

	$cols++;

	if ($cols <= 1)
	   echo "<th class=\"sel\">$syear</th>\n";
	else
	   echo "<th class=\"sel\" colspan=$cols>$syear</th>\n";

	# Ueberschrift der letzten Spalte, welche die Summierungen der
	# geplanten Aufwaende enthaelt.
	echo "<th class=\"sel\" rowspan=2>" . GetMessage($db, 337, "Summe") . "<br>" . GetMessage($db, 336, "Aufwand") . "</th>\n";

	if ($verrmodul) {
	   $query = "select wh_whg from key_whg where wh_num = $stdwhg";

	   if (!($reswhg = QueryDB($db, $query))) {
	      closeDB($db);
	      return;
	   }

	   $data = fetchDB($reswhg, 0);
	   $whg = $data[0];
	   echo "<th class=\"sel\" rowspan=2>" . GetMessage($db, 388, "Risiko<br>in&nbsp;%%") . "</th>\n";
	   echo "<th class=\"sel\" rowspan=2>" . GetMessage($db, 385, "Wert<br>ini&nbsp;%s", $whg) . "</th>\n";
	   echo "<th class=\"sel\" rowspan=2>" . GetMessage($db, 386, "Risiko&minus;<br>aufschlag") . "</th>\n";
	   echo "<th class=\"sel\" rowspan=2>" . GetMessage($db, 387, "Summen<br>ini&nbsp;%s", $whg) . "</th>\n";
	}

	echo "</tr>\n";
	$dt = $fdate;

	while (PerDateComp($dt, $ldate) >= 0) {
	   printf ("<th class=\"sel\">%s</th>\n", GetStrMonth($smon));
	   $smon++;
	   $dt = IncDate($periode, $dt);

	   if ($smon > 12) {
	      $syear++;
	      $smon = 1;
	   }
	}

	echo "</tr>\n";

	# Neues Projektobjekt. Es enthaelt die Tasknummerierung und Typen-
	# zuweisung der einzelnen Tasks.
	$project = new TaskNum($pl_num, $db);

	if (!$project->GetStatus()) {
	   Error(GetMessage($db, 338, "PlanPeriode: Interner Fehler beim Initialisieren des Objekts \"TaskNum\"!"));
	   closeDB($db);
	   return;
	}

	# Nun muessen wir die Tabelle mit Inhalten fuellen
	$query = "select ta_num, ta_id, ta_name, ta_meeting, ta_start,";
	$query .= "ta_duration, ta_level, ta_phase, ta_color, ta_plnum, ta_risiko ";
	$query .= "from task where ta_plnum = $pl_num order by ta_id";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return;
	}

	$numrows = numrowsDB($result);

	if ($numrows == 0) {
	   $ta_id = 0;
	   $ta_plnum = $pl_num;
	}

	$row = 0;
	$snum = "1";
	$ma = false;
        $done = false;
	$total = 0;
	$brutto_sum = 0;
	$netto_sum = 0;
	$risiko_sum = 0;

	while ($row < $numrows) {
	   if (!$ma) {
	      $data = fetchDB($result, $row);
	      $ta_num = $data[0];
	      $ta_id = $data[1];
	      $ta_name = $data[2];
	      $ta_meeting = $data[3];
	      $ta_start = $data[4];
	      $ta_duration = $data[5];
	      $ta_level = $data[6];
	      $ta_phase = $data[7];
	      $ta_color = $data[8];
	      $ta_plnum = $data[9];
	      $ta_risiko = $data[10];

	      # Der Task muss oben summiert sein, also in der Taskzeile
	      # selbst.
	      if ($ta_level == 1) {
	         $query = "select ta_num, ta_level, ta_risiko from task where ";
	         $query .= "ta_plnum = $ta_plnum and ta_id > $ta_id and ";
	         $query .= "ta_meeting = 0 order by ta_id";

	         if (!($resta = QueryDB($db, $query))) {
	            closeDB($db);
	            return;
		 }

		 $men = numrowsDB($resta);
		 $i = 0;
		 $al_hours = 0;

		 if ($verrmodul) {
	            $risc_sum = 0;
		    $netto = 0;
		    $brutto = 0;
		 }

		 while ($i < $men) {
		    $data = fetchDB($resta, $i);
		    $xnum = $data[0];
		    $xlevel = $data[1];
		    $risc = $data[2];

		    if ($xlevel <= $ta_level)
		       break;

		    # Ist das Verrechnungsmodul aktiv, benoetigen wir
		    # zusaetzlich den Tagsatz des jeweiligen Mitarbeiters,
		    # um die korrekten monetaeren Werte errechnen zu koennen.
		    if ($verrmodul) {
		       $query = "select al_hours, tg_amount from allocation ";
		       $query .= "left join tagsatz on tg_minum = al_ressource ";
		       $query .= "where al_task = $xnum and ";
		       $query .= "extract(epoch from tg_valid_from) <= al_pstart and ";
		       $query .= "(extract(epoch from tg_valid_to) >= al_pstart or tg_valid_to is NULL) ";
		       $query .= "order by tg_valid_from, tg_valid_to";

		       if (!($resver = QueryDB($db, $query))) {
		          closeDB($db);
			  return;
		       }

		       $jj = 0;
		       $xx = numrowsDB($resver);

		       while ($jj < $xx) {
		          $data = fetchDB($resver, $jj);
			  $al_hour = $data[0];
			  $tg_amount = $data[1];

			  $brutto += $tg_amount * $al_hour;
			  $rs = $al_hour / 100.0 * $risc;
			  $risc_sum += $rs * $tg_amount;
			  $netto += ($al_hour + $rs) * $tg_amount;
			  $al_hours += $al_hour;
			  $jj++;
		       }
		    } else {
		       $query = "select sum(al_hours) from allocation where ";
		       $query .= "al_task = $xnum";

		       if (!($resal = QueryDB($db, $query))) {
		          closeDB($db);
		          return;
		       }

		       $data = fetchDB($resal, 0);
		       $al_hours += $data[0];
		    }

		    $i++;
		 }
	      } else {
	         if ($verrmodul) {
		    $query = "select al_hours, tg_amount from allocation ";
		    $query .= "left join tagsatz on tg_minum = al_ressource ";
		    $query .= "where al_task = $ta_num and ";
		    $query .= "extract(epoch from tg_valid_from) <= al_pstart and ";
		    $query .= "(extract(epoch from tg_valid_to) >= al_pstart or tg_valid_to is NULL) ";
		    $query .= "order by tg_valid_from, tg_valid_to";

		    if (!($resver = QueryDB($db, $query))) {
		       closeDB($db);
		       return;
		    }

		    $al_hours = 0;
		    $risc_sum = 0;
		    $netto = 0;
		    $brutto = 0;
		    $jj = 0;
		    $xx = numrowsDB($resver);

		    while ($jj < $xx) {
		       $data = fetchDB($resver, $jj);
		       $al_hour = $data[0];
		       $tg_amount = $data[1];

		       $al_hours += $al_hour;
		       $brutto += $al_hour * $tg_amount;
		       $rs = $al_hour / 100.0 * $ta_risiko;
		       $risc_sum += $rs * $tg_amount;
		       $netto += ($al_hour + $rs) * $tg_amount;
		       $jj++;
		    }

		    $brutto_sum += $brutto;
		    $risiko_sum += $risc_sum;
		    $netto_sum += $netto;
		 } else {
	            $query = "select sum(al_hours) from allocation where ";
	            $query .= "al_task = $ta_num";

		    if (!($resal = QueryDB($db, $query))) {
		       closeDB($db);
		       return;
		    }

		    $data = fetchDB($resal, 0);
		    $al_hours = $data[0];
		 }
	      }
	   }

	   # Starrer Zeilenbegin ...
	   echo "<tr>\n";
	   if (!$ma) {
//	      $snum = GetTaskNum($pl_num, $ta_id, $ta_level, $ta_phase, $ta_meeting, $snum, &$typ, $db);
	      $snum = $project->Get_snum($row);
	      $art = $project->Get_type($row);

	      if ($art == "t")
		 $typ = true;
	      else
		 $typ = false;
	   }

	   # Diverse Aktionen / Buttons
	   echo "<td class=\"selakt\">";
	   $cal_linkf = "";
	   $cal_linkb = "";

	   if ($new && $ma) {
	      echo "<a name=\"edit\"></a>\n";		# Einsprungspunkt
	      echo "<input type=\"hidden\" name=\"ta_num\" value=\"$ta_num\">\n";
	      echo "<input type=\"hidden\" name=\"ta_phase\" value=\"$ta_phase\">\n";
	      echo "<input type=\"hidden\" name=\"func\" value=\"SaveMa\">\n";
	      ButtonImage("filesave.png", "plan", "Zeile speichern");
           } else if (!$ta_meeting && !$lock && $ta_level > 1 && $typ) {
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','edittask=$ta_num&$nav')\">";
	      echo "<img src=\"image/edit.png\" border=0 alt=\"Task editieren\"></a>";
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','taskadd=$ta_id&ta_num=$ta_num&ta_plnum=$ta_plnum&$nav')\">";
	      echo "<img src=\"image/new.png\" border=0 alt=\"Einfuegen\"></a>\n";
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','deletetask=$ta_num&ta_plnum=$ta_plnum&$nav')\">";
	      echo "<img src=\"image/editdelete.png\" border=0 alt=\"Task loeschen\"></a>";
	      $lev = GetPreviousLevel($db, $ta_num);

	      if ($lev != -1 && $lev >= $ta_level) {
	         echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','moveup=$ta_num&$nav')\">";
	         echo "<img src=\"image/up.png\" border=0 width=\"16\" height=\"16\" alt=\"Hinauf\">";
	      }

	      $lev = GetNextLevel($db, $ta_num);

	      if ($lev != -1 && $lev >= $ta_level) {
	         echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','movedown=$ta_num&$nav')\">";
	         echo "<img src=\"image/down.png\" border=0 width=\"16\" height=\"16\" alt=\"Hinunter\">";
	      }

	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','func=AllocMa&ta_num=$ta_num&$nav#edit')\">";
              echo "<img src=\"image/kverbosuser.png\" border=0 width=15 height=15 alt=\"Neuer Mitarbeiter\"></a>";
//	      $cal_linkf = "<a href=\"#\" onClick=\"javascript:open_window('calentry.php?header=1&ca_prnum=$pl_prnum&ca_task=$ta_num&func=plan', 'Kalender', 800, 600)\">";
//              $cal_linkb = "</a>";
	   } else if (!$lock) {
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','edittask=$ta_num&$nav')\">";
	      echo "<img src=\"image/edit.png\" border=0 alt=\"Task editieren\"></a>";
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','taskadd=$ta_id&ta_num=$ta_num&ta_plnum=$ta_plnum&$nav')\">";
	      echo "<img src=\"image/new.png\" border=0 alt=\"Einfuegen\"></a>\n";
	      echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','deletetask=$ta_num&ta_plnum=$ta_plnum&$nav')\">";
	      echo "<img src=\"image/editdelete.png\" border=0 alt=\"Task loeschen\"></a>";

//	      if ($ta_meeting) {
		 $lev = GetPreviousLevel($db, $ta_num);

		 if ($lev != -1 && $lev >= $ta_level) {
	            echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','moveup=$ta_num&$nav')\">";
	            echo "<img src=\"image/up.png\" border=0 width=\"16\" height=\"16\" alt=\"Hinauf\">";
		 }

		 $lev = GetNextLevel($db, $ta_num);

		 if ($lev != -1 && $lev >= $ta_level) {
	            echo "<a href=\"#\" onClick=\"javascript:MoveTo('plan.php','movedown=$ta_num&$nav')\">";
	            echo "<img src=\"image/down.png\" border=0 width=\"16\" height=\"16\" alt=\"Hinunter\">";
		 }
//	      }
	   } else
	      echo "&nbsp;";

           echo "</td>\n";
	   # Nummerierung
	   if (!$ma) {
	      if ($ta_meeting)
	         echo "<td class=\"sel\"><b>$snum</b></td>\n";
	      else
	         echo "<td class=\"sel\">$snum</td>\n";
           } else {
              echo "<td class=\"sel\">&nbsp;</td>\n";
           }

	   # Tasknamendarstellung abhaenging vom Level
	   if (!$ma) {
	      if ($ta_level == 1 || !$typ) {
	         if ($ta_meeting)
	            echo "<td class=\"seldkgray\" colspan=3>" . $cal_linkf . $ta_name . $cal_linkb . "</td>\n";
	         else if ($ta_level == 1)
	            echo "<td class=\"selltgray\" colspan=3>" . $cal_linkf . $ta_name . $cal_linkb . "</td>\n";
		 else
	            echo "<td class=\"selgray\" colspan=3>" . $cal_linkf . $ta_name . $cal_linkb . "</td>\n";
	      } else {
	         if ($ta_meeting)
	            echo "<td class=\"sel\" width=\"10%\"> </td><td class=\"seldkgray\" colspan=2>" . $cal_linkf . $ta_name . $cal_linkb . "</td>\n";
	         else
	            echo "<td class=\"sel\" width=\"10%\"> </td><td class=\"selgray\" colspan=2>" . $cal_linkf . $ta_name . $cal_linkb . "</td>\n";
	      }
           } else if ($ma && $new) {
              echo "<td colspan=2 class=\"sel\" width=\"20%\"> </td>\n";
              echo "<td class=\"sel\"><select name=\"name\">\n";
#              $query = "select mi_num, mi_vname, mi_nname from mitarbeiter ";
#              $query .= "where mi_plan = true order by mi_nname, mi_vname";
	      $query = "select ma_minum, mi_vname, mi_nname, kr_role from matopr ";
	      $query .= "left join mitarbeiter on mi_num = ma_minum ";
	      $query .= "left join key_role on kr_num = ma_role ";
	      $query .= "where ma_prnum = $pl_prnum ";
	      $query .= "order by mi_nname, mi_vname";
              $resmi = QueryDB($db, $query);

              if (!$resmi) {
                 return;
              }

              $nr = numrowsDB($resmi);
              $r = 0;

              while ($r < $nr) {
                 $data = fetchDB($resmi, $r);
                 $mi_num = $data[0];
                 $mi_vname = $data[1];
                 $mi_nname = $data[2];
		 $kr_role = $data[3];
                 echo "<option value=\"$mi_num\">$mi_nname $mi_vname, $kr_role</option>\n";
                 $r++;
              }

              echo "</select></td>\n";
           }

	   if (!$ta_meeting) {
	      if ($typ) {
	         $sein = GetStrEinheit($einheit);
	         echo "<td class=\"selgray\" align=\"right\">$ta_duration $sein</td>\n";
		 $dt = gmdate($dtformatshort, $ta_start);
		 $ed = GetEDate($einheit, $ta_start, $ta_duration);
		 $dte = gmdate($dtformatshort, $ed);
		 echo "<td class=\"selgray\" align=\"center\">$dt</td>\n";
		 echo "<td class=\"selgray\" align=\"center\">$dte</td>\n";
	      } else {
	         if ($ta_level == 1)
	            echo "<td colspan=3 class=\"selltgray\">&nbsp;</td>\n";
		 else
	            echo "<td colspan=3 class=\"selgray\">&nbsp;</td>\n";
	      }
	   } else {
	      echo "<td class=\"seldkgray\" align=\"center\">M</td>\n";
	      $dt = gmdate($dtformatshort, $ta_start);
	      echo "<td class=\"seldkgray\" align=\"center\" colspan=2>$dt</td>\n";
	   }

           # Anzeigen der Mitarbeiterrolle

#           if ($role) {
#              if ($ma && $new) {
#                 echo "<td class=\"sel\">";
#                 $query = "select kr_num, kr_role from key_role order by kr_num";
#                 $result2 = QueryDB($db, $query);

#                 if (!$result2)
#                    return;

#                 $nr = numrowsDB($result2);
#                 $r = 0;
#                 echo "<select name=\"role\">\n";

#                 while ($r < $nr) {
#                    $data = fetchDB($result2, $r);
#                    $kr_num = $data[0];
#                    $kr_role = $data[1];
#                    echo "<option value=\"$kr_num\">$kr_role</option>\n";
#                    $r++;
#                 }

#                 echo "</select></td>\n";
#              } else {
#	         if ($ta_level == 1)
#	            echo "<td class=\"selltgray\">&nbsp;</td>\n";
#	         else
#                    echo "<td class=\"selgray\">&nbsp;</td>\n";
#              }
#	   }

	   # Dynamischer Aufbau der restlichen Tabelle.
	   # Ab dem Startdatum werden Eingabezeilen ausgegeben, in die der
	   # Anwender Arbeitseinheiten eintragen kann.
	   $color = dechex($ta_color);
	   $len = strlen($color);

	   while ($len < 6) {
	      $color = "0" . $color;
	      $len++;
	   }

	   $dt = $fdate;

	   while (PerDateComp($dt, $ta_start) > 0) {
	      $dt = IncDate($periode, $dt);

	      if (!$typ && ! $ta_meeting && $ta_level == 1)
	         echo "<td class=\"sel\">&nbsp;</td>";
	      else
	         echo "<td class=\"sel\">&nbsp;</td>";
	   }

	   if ($ta_meeting)
	      $edate = $ta_start;
	   else
	      $edate = GetEDate($einheit, $ta_start, $ta_duration);

	   do {
	      if ($new && $ma) {
	         $tm = gmdate("j.n.Y", $dt);
	         $ad = explode(".", $tm);
	         $nm = "dt_" . (string)$ta_id . "_" . (string)$ad[1];
		 $nm .= "_" . (string)$ad[2];

		 if ($dt > $ab_datum || $rstufe == 1)
		    echo "<td class=\"sel\"><input type=\"text\" name=\"$nm\" size=6 maxlength=6></td>\n";
		 else
		    echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
	      } else {
	         if ($typ)
	            echo "<td style=\"background-color: #$color; border: 1px solid black;\">&nbsp;</td>\n";
	         else if ($ta_meeting)
	            echo "<td style=\"color: #$color;background-color: #969696;border: 1px solid black;\"><center>###</center></td>\n";
	         else if ($ta_level == 1)
	            echo "<td style=\"color: #$color;background-color: #dddddd; border: 1px solid black;\"><center>===</center></td>\n";
	         else
	            echo "<td style=\"color: #$color;background-color: #dddddd; border: 1px solid black;\"><center>===</center></td>\n";
	      }

	      $dt = IncDate($periode, $dt);
           }
	   while (PerDateComp($dt, $edate) >= 0);

	   while (PerDateComp($dt, $ldate) >= 0) {
	      $dt = IncDate($periode, $dt);

//	      if ($ta_level == 1)
//	         echo "<td class=\"sel\">&nbsp;</td>";
//	      else
	         echo "<td class=\"sel\">&nbsp;</td>";
	   }

	   # Ausfuellen der Summenspalte
	   if (($typ && !$ma) || $ta_level == 1) {
	      printf ("<td class=\"selltgray\" align=\"right\"><b><u>%s</u></b></td>\n", FormatNum($al_hours, 3));
	      $sum = 0;

	      if ($verrmodul) {
	         if ($ta_risiko > 0)
	            printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($ta_risiko, 3));
		 else
		    echo "<td class=\"sel\">&nbsp;</td>\n";

	         printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($brutto, 2));
		 printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($risc_sum, 2));
		 printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($netto, 2));
	      }
	   } else {
	      echo "<td class=\"sel\">&nbsp;</td>\n";

	      if ($verrmodul) {
	         echo "<td class=\"sel\">&nbsp;</td>";
	         echo "<td class=\"sel\">&nbsp;</td>";
	         echo "<td class=\"sel\">&nbsp;</td>";
	         echo "<td class=\"sel\">&nbsp;</td>";
	      }
	   }

	   if ($typ && !$ma) {
	      if ($ta_num == $tanum)
	         $sum = PrintMa($db, $fdate, $ldate, $ta_num, $color, $pl_num, $ressource, $lock);
	      else
	         $sum = PrintMa($db, $fdate, $ldate, $ta_num, $color, $pl_num, 0, $lock);

	      $total += $sum;
	   }

	   echo "</tr>\n";

	   if ($ma) {
              $ma = false;
              $done = true;
           }

	   if ($new && !$done && $ta_num == $id)
	      $ma = true;

	   if (!$ma)
	      $row++;
	}

	# Anfuegen der Summierungen

	if ($total > 0) {
#	   if ($role)
#	      $span = 9 + $tbcols;
#	   else
	      $span = 8 + $tbcols;

//	   if ($sum > 0) {
/*	   if (($typ && !$ma) || $ta_level == 1) {
	      echo "<tr><td class=\"sel\"colspan=$span>&nbsp;</td>";
	      printf("<td class=\"selltgray\" align=\"right\"><b><u>%s</u></b></td>\n", FormatNum($al_hours, 3));

	      if ($verrmodul) {
	         if ($ta_risiko > 0)
	            printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($ta_risiko, 3));
		 else
		    echo "<td class=\"sel\">&nbsp;</td>\n";

	         printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($brutto, 2));
		 printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($risc_sum, 2));
		 printf ("<td class=\"selnum\"><b>%s</b></td>", FormatNum($netto, 2));
	      }

	      echo "</tr>\n";
           }
*/
	   echo "<tr><td class=\"selnum\" colspan=$span>Gesamtsumme:</td>";
	   printf("<td class=\"selgray\" align=\"right\"><b><u>%s</u></b></td>\n", FormatNum($total, 3));

	   if ($verrmodul) {
	      echo "<td class=\"sel\">&nbsp;</td>\n";
	      printf ("<td class=\"selgray\" align=\"right\"><b>%s</b></td>\n", FormatNum($brutto_sum, 2));
	      printf ("<td class=\"selgray\" align=\"right\"><b>%s</b></td>\n", FormatNum($risiko_sum, 2));
	      printf ("<td class=\"selgray\" align=\"right\"><b>%s</b></td>\n", FormatNum($netto_sum, 2));
	   }

	   echo "</tr>\n";
	}

	echo "</table>\n";

        if ($new)
           echo "</form>\n";

	$ta_id++;

	if (!$lock) {
	   echo "<table class=\"indent\"><tr><td>";
	   ButtonLink("Task Anh&auml;ngen", "plan.php", "taskadd=$ta_id&ta_num=$ta_num&ta_plnum=$ta_plnum&$nav");
	   echo "</td></tr></table>";
	}

	closeDB($db);
}

function AskPlanOverload($db, $res_hours, $plan, $pts, $mon, $year) {
	global $periode;
	global $phase;
	global $role;
	global $dtformatshort;
	global $menu;
	global $headline;

	$pl_num = $_REQUEST['pl_num'];
	$ta_num = $_REQUEST['ta_num'];
	$name = $_REQUEST['name'];
#	$rolem = $_REQUEST['role'];

	if ($phase)
	   $ta_phase = $_REQUEST['ta_phase'];

	$query = "select mi_nname, mi_vname from mitarbeiter where ";
	$query .= "mi_num = $name";

	if (!($result = QueryDB($db, $query)))
	   return;
	   
	$data = fetchDB($result, 0);
	$mi_nname = $data[0];
	$mi_vname = $data[1];

	echo "<form name=\"Overload\" action=\"plan.php\" method=\"post\">\n";
	echo "<input type=\"hidden\" name=\"func\" value=\"SaveMa\">\n";
	echo "<input type=\"hidden\" name=\"pl_num\" value=\"$pl_num\">\n";
	echo "<input type=\"hidden\" name=\"ta_num\" value=\"$ta_num\">\n";
	echo "<input type=\"hidden\" name=\"name\" value=\"$name\">\n";
#	echo "<input type=\"hidden\" name=\"role\" value=\"$rolem\">\n";
	echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
	echo "<input type=\"hidden\" name=\"headline\" value=\"$headline\">\n";
	echo "<input type=\"hidden\" name=\"yes\" value=\"yes\">\n";

	if ($phase)
	   echo "<input type=\"hidden\" name=\"ta_phase\" value=\"$ta_phase\">\n";

	foreach ($_REQUEST as $key => $pstart) {
	   $fr = substr($key, 0, 3);

	   if ($fr == "dt_")
	      echo "<input type=\"hidden\" name=\"$key\" value=\"$pstart\">\n";
	}

	$sum = $plan + $res_hours;
?>
<table border=2 class="alarm">
   <tr><td colspan=2><big>Warnung!</big><br><br>
           Die Ressource <font color="white"><? echo "$mi_nname $mi_vname"; ?></font> soll mit weiteren
	   <font color="white"><? echo FormatNum($plan, 3); ?></font> PT's in der Periode
	   <font color="white"><? echo "$mon/$year"; ?></font> gebucht werden. Dadurch
	   w&uuml;rde die Ressource auf insgesamt <font color="white"><? echo FormatNum($sum, 3); ?></font>
	   PT's verplant werden. In dieser Periode stehen jedoch nur
	   <font color="white"><? echo "$pts"; ?></font> PT's zur Verf&uuml;gung!<br>
	   <br>
	   Wollen Sie dennoch die eingegebenen Planwerte f&uuml;r diese
	   Ressource speichern?
      </td>
   </tr>
   <tr>
      <td><center>
<?
	Button("Planwerte speichern", "Overload");
?>
          </center>
      </td>
      <td><center>
<?
	ButtonLink("Abbrechen", "plan.php", "editplan=$pl_num&menu=$menu&headline=$headline");
?>
      </center></td>
   </tr>
</table>
</form>
<?
}

function SaveMa($save=true) {
	global $periode;
	global $phase;
	global $role;

	$pl_num = $_REQUEST['pl_num'];
	$ta_num = $_REQUEST['ta_num'];
	$name = $_REQUEST['name'];

#	if ($role)
#	   $rolem = $_REQUEST['role'];

	if ($phase)
	   $ta_phase = $_REQUEST['ta_phase'];
	else
	   $ta_phase = 0;

	$err = 0;

	if (!isset($pl_num) || $pl_num <= 0) {
	   Error("Interner Fehler: Plannumer fehlt oder ist ung&uuml;ltig!");
	   $err = 1;
	}

	if (!isset($ta_num) || $ta_num <= 0) {
	   Error("Interner Fehler: Tasknummer fehlt oder ist ung&uuml;ltig!");
	   $err = 1;
	}

	if (!isset($name) || $name <= 0) {
	   Error("Interner Fehler: Mitarbeiternummer fehlt oder ist ung&uuml;ltig!");
	   $err = 1;
	}

#	if ($role && (!isset($rolem) || $rolem <= 0)) {
#	   Error("Interner Fehler: Rollenbezeichnung fehlt!");
#	   $err = 1;
#	}

	if ($err)
	   return false;

//	if (!$role)
//	   $rolem = 1;

	$db = OpenDB();

	# Da sich die Mitarbeiterrollenzuweisung geaendert hat (03.04.2007)
	# muessen wir die Rolle aus dem zugewiesenen Mitarbeiter extrahieren.
	# Dazu benoetigen wir zunaechst die Projektnummer.
	if ($role) {
	   $query = "select pl_prnum from plan where pl_num = $pl_num";

	   if (!($result = QueryDB($db, $query))) {
	      closeDB($db);
	      return;
	   }

	   if (numrowsDB($result) > 0) {
	      $data = fetchDB($result, 0);
	      $pr_num = $data[0];
	   } else {
	      closeDB($db);
	      Error("Interner Fehler: Projektnummer wurde nicht gefunden!");
	      return false;
	   }

	   $query = "select ma_role from matopr where ";
	   $query .= "ma_minum = $name and ma_prnum = $pr_num";

	   if (!($result = QueryDB($db, $query))) {
	      closeDB($db);
	      return false;
	   }

	   if (numrowsDB($result) > 0) {
	      $data = fetchDB($result, 0);
	      $rolem = $data[0];
	   } else {
	      closeDB($db);
	      Error("Interner Fehler: Mitarbeiterrolle wurde nicht gefunden!");
	      return false;
	   }
	}

	# Zunaechst muessen wir sicher stellen, das dem Task nicht bereits
	# diese Ressource hinzugefuegt wurde.
	$query = "select al_num from allocation where al_ressource = $name ";
	$query .= "and al_task = $ta_num";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	$anz = numrowsDB($result);
	$query = "select co_allocation from counter";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$co_allocation = $data[0];
	QueryDB($db, "begin");

	# Falls die Ressource bereits zugeordnet war, wird sie hier geloescht.
	$query = "delete from allocation where al_ressource = $name ";
	$query .= "and al_task = $ta_num";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return false;
	}

	foreach ($_REQUEST as $key => $pstart) {
	   $fr = substr($key, 0, 3);

	   if ($fr == "dt_") {
	      $p = strpos($key, "_", 3);
	      $ta_id = substr($key, 3, $p-3);
	      $q = strpos($key, "_", $p+1);
	      $mon = substr($key, $p+1, $q-($p+1));
	      $year = substr($key, $q+1);
	      $pstart = str_replace(",", ".", $pstart);

	      if (!isset($pstart) || $pstart <= 0.0)
	         continue;

	      $al_pstart = gmmktime(0, 0, 0, $mon, 1, $year);

	      # Pruefen, ob die Ressource in der aktuellen Periode ueberbucht
	      # ist. Falls ja, erscheint ein rotes Warnfenster, welches den
	      # Anwender darauf hinweist.
	      $res_hours = GetRessource($db, $name, $al_pstart);
	      $pts = GetPT($al_pstart);

	      if (!$save && ($res_hours + $pstart) > $pts) {
	         AskPlanOverload($db, $res_hours, $pstart, $pts, $mon, $year);
		 QueryDB($db, "rollback");
		 closeDB($db);
		 include('footer.inc');
		 exit;
	      }

	      switch ($periode) {
	         case 1: $al_pduration = 364; break;
	         case 2: $al_pduration = 91; break;
	         case 3: $al_pduration = daysinmonth($mon, $year); break;
	         case 4: $al_pduration = 1; break;
	         default: $al_pduration = daysinmonth($mon, $year); break;
	      }

              $co_allocation++;
              $query = "insert into allocation (al_num, al_task, al_ressource,";
              $query .= "al_hours, al_phase, al_pstart, al_pduration";

	      if ($role)
	         $query .= ",al_role";

              $query .= ") values ($co_allocation, $ta_num, $name, $pstart, ";
              $query .= "$ta_phase, $al_pstart, $al_pduration";

	      if ($role)
	         $query .= ", $rolem";

	      $query .= ")";

              if (!QueryDB($db, $query)) {
                 QueryDB($db, "rollback");
                 closeDB($db);
                 return false;
              }
           }
        }

        $query = "update counter set co_allocation = $co_allocation";

        if (!QueryDB($db, $query)) {
           QueryDB($db, "rollback");
           closeDB($db);
           return false;
        }

        QueryDB($db, "commit");
        Journal(300, "plan.php: SaveMa: task=$ta_num; ressource=$name", $db);
        closeDB($db);
        return true;
}

function SaveUpMa() {
        global $periode;
	global $phase;
	global $role;

        $pl_num = $_REQUEST['pl_num'];
        $ta_num = $_REQUEST['ta_num'];
	$ressource = $_REQUEST['ressource'];

	if ($phase)
	   $al_phase = $_REQUEST['al_phase'];
	else
	   $al_phase = 0;

	if ($role)
	   $al_role = $_REQUEST['al_role'];
//	else
//	   $al_role = 1;

        $err = 0;

        if (!isset($pl_num) || $pl_num <= 0) {
           Error("Interner Fehler: Plannumer fehlt oder ist ung&uuml;ltig!");
           $err = 1;
        }

        if (!isset($ta_num) || $ta_num <= 0) {
           Error("Interner Fehler: Tasknummer fehlt oder ist ung&uuml;ltig!");
           $err = 1;
        }

        if ($err)
           return false;

        $db = OpenDB();
	$query = "select co_allocation from counter";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$co_allocation = $data[0];
	$count = $co_allocation;

	QueryDB($db, "begin");

        foreach ($_REQUEST as $key => $pstart) {
           $fr = substr($key, 0, 3);

           if ($fr == "dt_") {
              $p = strpos($key, "_", 3);
              $al_num = substr($key, 3, $p-3);
              $q = strpos($key, "_", $p+1);
              $mon = substr($key, $p+1, $q-($p+1));
              $year = substr($key, $q+1);
	      $pstart = str_replace(",", ".", $pstart);

	      if ((!isset($pstart) || $pstart <= 0) && $al_num > 0) {
	         $query = "delete from allocation where al_num = $al_num";

		 if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
		    closeDB($db);
		    return false;
		 }

	         continue;
	      }

	      if ($al_num == 0 && $pstart > 0) {
	         $al_pstart = gmmktime(0, 0, 0, $mon, 1, $year);

	         switch ($periode) {
	            case 1: $al_pduration = 364; break;
	            case 2: $al_pduration = 91; break;
	            case 3: $al_pduration = 30; break;
	            case 4: $al_pduration = 1; break;
	            default: $al_pduration = 30; break;
	         }

		 $co_allocation++;
	         $query = "insert into allocation (al_num, al_task,";
		 $query .= "al_ressource, al_hours, al_phase, al_pstart,";

		 if ($role)
		    $query .= "al_pduration, al_role) values ($co_allocation,";
		 else
		    $query .= "al_pduration) values ($co_allocation,";
		    
		 $query .= "$ta_num, $ressource, $pstart, $al_phase,";

		 if ($role)
		    $query .= "$al_pstart, $al_pduration, $al_role)";
		 else
		    $query .= "$al_pstart, $al_pduration)";
	      } else if ($al_num > 0 && $pstart > 0) {
		 $query = "update allocation set al_hours = $pstart where ";
		 $query .= "al_num = $al_num";
	      } else
	         continue;

	      if (!QueryDB($db, $query)) {
		 QueryDB($db, "rollback");
		 closeDB($db);
		 return false;
	      }
	   }
	}

	if ($count < $co_allocation) {
	   $query = "update counter set co_allocation = $co_allocation";

	   if (!QueryDB($db, $query)) {
	      QueryDB($db, "rollback");
	      closeDB($db);
	      return false;
	   }
	}

	QueryDB($db, "commit");
	Journal(300, "plan.php: SaveUpMa: task=$ta_num; ressource=$ressource", $db);
	closeDB($db);
	return true;
}

# Folgende Funktion fragt den Anwender, ob er die IST-Werte auch tatsaechlich
# uebernehmen will.
function AskIstPlan($pl_num) {
	global $phase;
	global $dtformatshort;
	global $pjcopy;

	$headline = $_REQUEST['headline'];
	$menu = $_REQUEST['menu'];
	$pl_prnum = $_REQUEST['pl_prnum'];
	$pl_status = $_REQUEST['pl_status'];
	$nav = "editcopy=$pl_num&menu=$menu&pl_prnum=$pl_prnum&";
	$nav .= "pl_status=$pl_status&func=CopyPlan&headline=21&";
	$nav .= "istdate='+document.AskIstPlan.istdate.value+'";
	$datum = time();
	$mon = gmdate("n", $datum);
	$year = gmdate("Y", $datum);
	$day = gmdate("j", $datum);

	if ($pjcopy != 3) {
	   $mon--;

	   if ($mon < 1) {
	      $mon = 12;
	      $year--;
	   }

	   if ($day < (daysinmonth($mon, $year) / 2)) {
	      $mon--;

	      if ($mon < 1) {
	         $mon = 12;
	         $year--;
	      }
	   }

	   $datum = gmmktime(0, 0, 0, $mon, 1, $year);
	} else {
	   $datum = 0;
	   $db = OpenDB();
	   $query = "select ab_datum from abschluss where ";
	   $query .= "ab_prnum = $pl_prnum order by ab_datum desc";

	   if (!($result = QueryDB($db, $query))) {
	      closeDB($db);
	      return;
	   }

	   if (numrowsDB($result) > 0) {
	      $data = fetchDB($result, 0);
	      $ab_datum = $data[0];
	      $lab = gmdate($dtformatshort, $ab_datum);
	   } else
	      $lab = GetMessage($db, 404, "(Projekt wurde bisher noch nicht abgeschlossen)");
	}
?>
<br>
<form name="AskIstPlan" action="plan.php" method="post">
<table class="input">
   <tr><th class="sel" colspan=3><? Output(-1, 393, "Plan kopieren"); ?></th></tr>
<?
	if ($pjcopy == 1) {
?>
   <tr><td colspan=3><br><? Output(-1, 394, "Bis zu welcher Periode sollen die IST-Werte als
        Planwerte &uuml;bernommen werden?"); ?>
        <br><br>
      </td>
   </tr>
   <tr>
      <td><? Output(-1, 395, "IST-Werte &uuml;bernehmen bis (%s):", GetVisualDate($dtformatshort, true)); ?></td>
      <td colspan=2><input type="text" name="istdate" value="<? echo GetShortDate($datum) ?>" maxlength=7 size=7></td>
   </tr>
<?
	} else if ($pjcopy == 2) {
?>
   <tr>
      <td colspan=3><? Output(-1, 397, "Beim Kopieren des Plans werden die IST-Werte bis zum %s &uuml;bernommen!", GetShortDate($datum)); ?>
         <input type="hidden" name="istdate" value="<? echo GetShortDate($datum); ?>">
      </td>
   </tr>
<?
	} else {
?>
   <tr>
      <td colspan=3><? Output(-1, 402, "Die IST-Werte des Projekts %s werden bis zum %s (letzter Teilprojektabschluss) &uuml;bernommen!", $pl_prnum, $lab); ?>
         <input type="hidden" name="istdate" value="0">
      </td>
   </tr>
<?
	}
?>
   <tr>
      <td><center><input type="button" name="yes" value="<? Output(-1, 393, "Plan kopieren"); ?>" onClick="javascript:MoveTo('plan.php','yes=yes&<? echo "$nav"; ?>')"></center></td>
      <td><? if ($pjcopy == 1) { ?><center><input type="button" name="no" value="<? Output(-1, 396, "Planwerte unver&auml;ndert &uuml;bernehmen"); ?>" onClick="javascript:MoveTo('plan.php','no=no&<? echo "$nav"; ?>')"></center> <? } ?></td>
      <td><center><input type="button" name="cancel" value="<? Output(-1, 49, "Abbrechen"); ?>" onClick="javascript:MoveTo('plan.php','cancel=cancel&<? echo "$nav"; ?>')"></center></td>
   </tr>
</table>
</form>
<?php
}

# Folgende Funktion kopiert einen bestehenden Plan und erzeugt eine Instanz
# davon. Anschliessend kann diese Instanz bearbeitet werden.
#
function editcopy($pl_num, $plis=false, $doit=false) {
	global $leneinheit;
	global $periode;
	global $role;
	global $pmlight;
	global $pjcopy;

	$pl_prnum = $_REQUEST['pl_prnum'];
	$pl_status = $_REQUEST['pl_status'];

	if (!isset($pl_prnum) || $pl_prnum <= 0) {
	   Error(GetMessage(-1, 389, "Interner Fehler: Projektnummer fehlt!"));
	   return false;
	}

	if (!isset($pl_status) || $pl_status <= 0) {
	   Error(GetMessage(-1, 390, "Interner Fehler: Projektstatus wurde nicht &uuml;bergeben!"));
	   return false;
	}

	if (!$doit) {
	   AskIstPlan($pl_num);
	   require('footer.inc');
	   exit(0);
	}

	if ($plis || $pjcopy == 2)
	   $istdate = $_REQUEST['istdate'];
	else
	   $istdate = 0;

	if (!isset($istdate)) {
	   Error(GetMessage(-1, 391, "Es wurde kein Datum angegeben, bis zu welchem die IST-Werte &uuml;bernommen werden sollen!"));
	   return false;
	} else if ($plis || $pjcopy == 2) {
	   $edt = explode(GetDateSep(), $istdate);
	   $istdate = gmmktime(0, 0, 0, $edt[0], daysinmonth($edt[0], $edt[1]), $edt[1]);
	}

	$db = OpenDB();
	$query = "select pl_lfd, pl_prnum, pl_status, pl_comment from plan where ";
	$query .= "pl_num = $pl_num";
	$result = QueryDB($db, $query);

	if (!$result) {
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$pl_lfd = $data[0];
	$pl_prnum = $data[1];
	$pl_status = $data[2];
	$pl_comment = $data[3];
	closeDB($db);
	unset($db);

	$new_pl_num = SaveNewPlan();

	if (!$new_pl_num)
	   return false;

	$db = OpenDB();
	# Den Kommentar zum neuen Plan hinzufuegen (nur wenn keine strikte
	# Periodensicht ($pmlight == false) gewaehlt wurde)
	if (!$pmlight) {
	   $query = "update plan set pl_comment = '$pl_comment' where ";
	   $query .= "pl_num = $new_pl_num";

	   if (!QueryDB($db, $query)) {
	      closeDB($db);
	      return false;
	   }
	}

	$query = "select co_task, co_allocation from counter";
	$result = QueryDB($db, $query);

	if (!$result) {
	   QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	   closeDB($db);
	   return false;
	}

	$data = fetchDB($result, 0);
	$co_task = $data[0] + 1;
	$co_allocation = $data[1] + 1;

	# Wenn die IST-Werte des PJ bis zum Datum des letzten
	# Teilprojektabschluss uebernommen werden sollen,
	# benoetigen wir das Datum des letzten TPA.
	if ($pjcopy == 3) {
	   $query = "select ab_datum from abschluss where ";
	   $query .= "ab_prnum = $pl_prnum order by ab_datum desc";

	   if (!($resab = QueryDB($db, $query))) {
	      QueryDB($db, "rollback");
	      QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	      closeDB($db);
	      return false;
	   }

	   if (numrowsDB($resab) > 0) {
	      $data = fetchDB($resab, 0);
	      $ab_datum = $data[0];
	   } else
	      $ab_datum = 0;

	   if ($ab_datum == 0)
	      $plis = 0;
	   else
	      $istdate = $ab_datum;
	}

	# Auslesen der Tasks. In der folgenden Schleife werden die Tasks
	# kopiert und neu eingefuegt.
	$query = "select ta_num, ta_id, ta_depend, ta_deptype, ta_name, ta_color,";
	$query .= "ta_shape, ta_meeting, ta_start, ta_duration, ta_complete,";
	$query .= "ta_fixed_start, ta_priority, ta_level, ta_phase, ta_notiz, ta_risiko, ta_hash ";
	$query .= "from task where ta_plnum = $pl_num order by ta_id";
	$result = QueryDB($db, $query);

	if (!$result) {
	   QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	   closeDB($db);
	   return false;
	}

	$numrows = numrowsDB($result);
	$rows = 0;
	QueryDB($db, "begin");

	while ($rows < $numrows) {
	   $data = fetchDB($result, $rows);
	   $ori_ta_num = $data[0];
	   $ta_id = $data[1];
	   $ta_depend = $data[2];
	   $ta_deptype = $data[3];
	   $ta_name = addslashes($data[4]);
	   $ta_color = $data[5];
	   $ta_shape = $data[6];
	   $ta_meeting = $data[7];
	   $ta_start = $data[8];
	   $ta_duration = $data[9];
	   $ta_complete = $data[10];
	   $ta_fixed_start = $data[11];
	   $ta_priority = $data[12];
	   $ta_level = $data[13];
	   $ta_phase = $data[14];
	   $ta_notiz = $data[15];
	   $ta_risiko = $data[16];
	   $ta_hash = $data[17];
	   $ta_num = $co_task;
	   $ta_plnum = $new_pl_num;

	   if (!isset($ta_fixed_start))
	      $ta_fixed_start = 0;

	   if (!isset($ta_risiko))
	      $ta_risiko = 0;

	   if (!isset($ta_depend) || strlen($ta_depend) == 0)
	      $ta_depend = "NULL";

	   # Ende des Task als Datum
	   $ta_end = $ta_start + ($ta_duration * 86400);
	   # Kopie des Task speichern
	   $query = "insert into task (ta_num, ta_plnum, ta_id, ta_depend,";
	   $query .= "ta_deptype, ta_name, ta_color, ta_shape, ta_meeting,";
	   $query .= "ta_start, ta_duration, ta_complete, ta_fixed_start,";
	   $query .= "ta_priority, ta_level, ta_phase, ta_notiz, ta_risiko, ta_hash) values ";
	   $query .= "($ta_num, $ta_plnum, $ta_id, $ta_depend, $ta_deptype,";
	   $query .= "'$ta_name', $ta_color, '$ta_shape', $ta_meeting,";
	   $query .= "$ta_start, $ta_duration, $ta_complete, $ta_fixed_start,";
	   $query .= "$ta_priority, $ta_level, $ta_phase, '$ta_notiz', $ta_risiko, '$ta_hash')";
	   $result2 = QueryDB($db, $query);

	   if (!$result2) {
	      QueryDB($db, "rollback");
	      QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	      closeDB($db);
	      return false;
	   }

	   if (!$plis && $pjcopy != 2) {
	      # Auslesen der Planwerte zum Task.
	      $query = "select al_ressource, al_hours, al_phase, al_pstart,";

	      if ($role)
	         $query .= "al_pduration, al_role from allocation where ";
	      else
	         $query .= "al_pduration from allocation where ";

	      $query .= "al_task = $ori_ta_num order by al_num";
	      $result3 = QueryDB($db, $query);

	      if (!$result3) {
		 QueryDB($db, "rollback");
		 QueryDB($db, "delete from plan where pl_num = $new_pl_num");
		 closeDB($db);
		 return false;
	      }

	      $nr = numrowsDB($result3);
	      $r = 0;

	      while ($r < $nr) {
	         $data = fetchDB($result3, $r);
	         $al_ressource = $data[0];
	         $al_hours = $data[1];
	         $al_phase = $data[2];
	         $al_pstart = $data[3];
	         $al_pduration = $data[4];

		 if ($role)
	            $al_role = $data[5];

	         $al_num = $co_allocation;
	         $al_task = $ta_num;

	         if (!isset($al_phase))
	            $al_phase = $ta_phase;

	         if (!isset($al_pduration))
	            $al_pduration = 1;

		 if (!$role)
		    $al_role = 1;

	         $query = "insert into allocation (al_num, al_task,";
		 $query .= "al_ressource, al_hours, al_phase, al_pstart,";

		 if ($role)
	            $query .= "al_pduration, al_role) values ($al_num, $al_task,";
		 else
	            $query .= "al_pduration) values ($al_num, $al_task,";

	         $query .= "$al_ressource, $al_hours, $al_phase, $al_pstart,";

		 if ($role)
	            $query .= "$al_pduration, $al_role)";
		 else
	            $query .= "$al_pduration)";

	         if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
	            QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	            closeDB($db);
	            return false;
	         }

	         $co_allocation++;
	         $r++;
	      }
	   } else {
	      # Aus der Tabelle "wdone" heraus werden die IST-Werte ermittelt
	      # und mit Hilfe des Hashwerts den richtigen Tasks zugewiesen.
	      #
	      # Ist ein IST-Wert frueher als das Startdatum eingetragen, aendert
	      # sich das Startdatum und wenn der IST-Wert nach dem Endedatum
	      # eingetragen wurde, dann aendert sich das Endedatum des Tasks!
	      #
	      $query = "select wd_hours/$leneinheit, wd_datum, wd_minum from wdone, task where ";
	      $query .= "ta_num = wd_task and ta_hash = '$ta_hash' and wd_prnum = $pl_prnum and ";
	      $query .= "wd_datum <= $istdate ";
	      $query .= "order by wd_minum, wd_datum";

	      if (!($resma = QueryDB($db, $query))) {
	         QueryDB($db, "rollback");
		 QueryDB($db, "delete from plan where pl_num = $new_pl_num");
		 closeDB($db);
		 return false;
	      }

	      $anzma = numrowsDB($resma);
	      $maza = 0;
	      $end = $ta_start + ($ta_duration * 86400);
	      $akt_von = 0;
	      $akt_bis = 0;
	      $al_hours = 0;
	      $old_wdminum = 0;
	      $task_flag = false;

	      while ($maza < $anzma) {
	         $data = fetchDB($resma, $maza);
		 $wd_hours = $data[0];
		 $wd_datum = $data[1];
		 $wd_minum = $data[2];
		 $lo_tahash = $data[3];

		 if ($maza == 0) {
		    $mon = gmdate("n", $wd_datum);
		    $year = gmdate("Y", $wd_datum);
		    $akt_von = gmmktime(0, 0, 0, $mon, 1, $year);
		    $akt_bis = gmmktime(0, 0, 0, $mon, daysinmonth($mon, $year), $year);
		    $old_wdminum = $wd_minum;
		 }

		 if ($old_wdminum != $wd_minum || ($akt_von < $wd_datum && $akt_bis < $wd_datum)) {
		    # Speichern der Periode
		    $al_num = $co_allocation;
		    $al_task = $ta_num;
		    $al_pstart = $akt_von;
		    $al_phase = $ta_phase;
		    $al_ressource = $old_wdminum;
		    $al_pduration = (GetUltimo($al_pstart) - $al_pstart) / 86400;
		    # Wir brauchen noch die Rolle, sofern die Einstellungen das
		    # verlangen!
		    if ($role) {
		       $query = "select al_role from allocation where ";
		       $query .= "al_task = $ori_ta_num and al_ressource = $al_ressource";

		       if (!($resal = QueryDB($db, $query))) {
		          QueryDB($db, "rollback");
	                  QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	                  closeDB($db);
	                  return false;
	               }

		       if (numrowsDB($resal) > 0) {
		          $data = fetchDB($resal, 0);
			  $al_role = $data[0];
		       }
		    }

	            $query = "insert into allocation (al_num, al_task,";
		    $query .= "al_ressource, al_hours, al_phase, al_pstart,";

		    if ($role && isset($al_role))
	               $query .= "al_pduration, al_role) values ($al_num, $al_task,";
		    else
	               $query .= "al_pduration) values ($al_num, $al_task,";
			  
	            $query .= "$al_ressource, $al_hours, $al_phase, $al_pstart,";

		    if ($role && isset($al_role))
	               $query .= "$al_pduration, $al_role)";
		    else
	               $query .= "$al_pduration)";

	            if (!QueryDB($db, $query)) {
		       QueryDB($db, "rollback");
	               QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	               closeDB($db);
	               return false;
	            }

	            $co_allocation++;
		    $mon = gmdate("n", $wd_datum);
		    $year = gmdate("Y", $wd_datum);
		    $akt_von = gmmktime(0, 0, 0, $mon, 1, $year);
		    $akt_bis = gmmktime(0, 0, 0, $mon, daysinmonth($mon, $year), $year);
		    $old_wdminum = $wd_minum;
		    $al_hours = 0;
		 }

		 if ($wd_datum > $ta_end) {
		    $ta_duration = ($wd_datum - $ta_start) / 86400;
	            $ta_end = $ta_start + ($ta_duration * 86400);
		    $task_flag = true;
		 }

		 $al_hours += $wd_hours;
		 $maza++;
	      }

	      # Speichern der Periode
	      # Hier wird der letzte Datensatz weggespeichert!
	      if ($anzma > 0) {
		 $al_num = $co_allocation;
		 $al_task = $ta_num;
		 $al_pstart = $akt_von;
		 $al_phase = $ta_phase;
		 $al_ressource = $wd_minum;
		 $al_pduration = (GetUltimo($al_pstart) - $al_pstart) / 86400;
		 # Wir brauchen noch die Rolle, sofern die Einstellungen das
		 # verlangen!
		 if ($role) {
		    $query = "select al_role from allocation where ";
		    $query .= "al_task = $ori_ta_num and al_ressource = $al_ressource";

		    if (!($resal = QueryDB($db, $query))) {
		       QueryDB($db, "rollback");
		       QueryDB($db, "delete from plan where pl_num = $new_pl_num");
		       closeDB($db);
		       return false;
		    }

		    if (numrowsDB($resal) > 0) {
		       $data = fetchDB($resal, 0);
		       $al_role = $data[0];
		    }
		 }

		 $query = "insert into allocation (al_num, al_task,";
		 $query .= "al_ressource, al_hours, al_phase, al_pstart,";

		 if ($role && isset($al_role))
		    $query .= "al_pduration, al_role) values ($al_num, $al_task,";
		 else
		    $query .= "al_pduration) values ($al_num, $al_task,";

		 $query .= "$al_ressource, $al_hours, $al_phase, $al_pstart,";

		 if ($role && isset($al_role))
		    $query .= "$al_pduration, $al_role)";
		 else
		    $query .= "$al_pduration)";

		 if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
		    QueryDB($db, "delete from plan where pl_num = $new_pl_num");
		    closeDB($db);
		    return false;
		 }

		 $co_allocation++;

		 if ($wd_datum > $ta_end) {
		    $ta_duration = ($wd_datum - $ta_start) / 86400;
	            $ta_end = $ta_start + ($ta_duration * 86400);
		    $task_flag = true;
		 }
	      }

	      # Wenn ($task_flag == true) ist, dann gab es IST-Efassungen
	      # die Ausserhalb des Tasks liegen. In diesem Fall muss das
	      # Beginndatum und/oder die Laufzeit des Tasks entsprechend
	      # geaendert werden.
	      #
	      if ($task_flag) {
		 $query = "update task set ta_duration = $ta_duration ";
		 $query .= "where ta_num = $ta_num";

		 if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
	            QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	            closeDB($db);
	            return false;
		 }
	      }

	      # Auslesen der Planwerte zum Task.
	      # Alle Planwerte die juenger als $istdate sind, muessen gefunden
	      # und ebenfalls eingefuegt werden!
	      $query = "select al_ressource, al_hours, al_phase, al_pstart,";

	      if ($role)
	         $query .= "al_pduration, al_role from allocation where ";
	      else
	         $query .= "al_pduration from allocation where ";

	      $query .= "al_task = $ori_ta_num and al_pstart > $istdate order by al_ressource, al_num";
	      $result3 = QueryDB($db, $query);

	      if (!$result3) {
		 QueryDB($db, "rollback");
		 QueryDB($db, "delete from plan where pl_num = $new_pl_num");
		 closeDB($db);
		 return false;
	      }

	      $nr = numrowsDB($result3);
	      $r = 0;

	      while ($r < $nr) {
	         $data = fetchDB($result3, $r);
	         $al_ressource = $data[0];
	         $al_hours = $data[1];
	         $al_phase = $data[2];
	         $al_pstart = $data[3];
	         $al_pduration = $data[4];

		 if ($role)
	            $al_role = $data[5];

	         $al_num = $co_allocation;
	         $al_task = $ta_num;

	         if (!isset($al_phase))
	            $al_phase = $ta_phase;

	         if (!isset($al_pduration))
	            $al_pduration = (GetUltimo($al_pstart) - $al_pstart) / 86400;

	         $query = "insert into allocation (al_num, al_task,";
		 $query .= "al_ressource, al_hours, al_phase, al_pstart,";

		 if ($role)
	            $query .= "al_pduration, al_role) values ($al_num, $al_task,";
		 else
	            $query .= "al_pduration) values ($al_num, $al_task,";

	         $query .= "$al_ressource, $al_hours, $al_phase, $al_pstart,";

		 if ($role)
	            $query .= "$al_pduration, $al_role)";
		 else
	            $query .= "$al_pduration)";

	         if (!QueryDB($db, $query)) {
		    QueryDB($db, "rollback");
	            QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	            closeDB($db);
	            return false;
	         }

	         $co_allocation++;
	         $r++;
	      }
	   }

	   $co_task++;
	   $rows++;
	}

	$co_task--;
	$co_allocation--;
	$query = "update counter set co_task = $co_task, co_allocation = $co_allocation";
	$result2 = QueryDB($db, $query);

	if (!$result2) {
	   QueryDB($db, "rollback");
	   QueryDB($db, "delete from plan where pl_num = $new_pl_num");
	   closeDB($db);
	   return false;
	}

	QueryDB($db, "commit");
	Journal(200, "plan.php: editcopy: alte pl_num=$pl_num; neue pl_num=$new_pl_num; projekt=$pl_prnum", $db);
	closeDB($db);
	return true;
}

# Folgende Funktion speichert den Kommentar zu einem Plan. Dabei wird der
# TIMESTAMP nicht neu gesetzt!
#
function SavePlanComment() {
	global $pmlight;

	$pl_num = $_REQUEST['pl_num'];
	$pl_comment = $_REQUEST['pl_comment'];

	if (!isset($pl_num) || $pl_num <= 0) {
	   Error("Interner Fehler: Plannummer fehlt in SavePlanComment!");
	   return;
	}

	$db = OpenDB();
	$query = "update plan set pl_comment = '$pl_comment' where ";
	$query .= "pl_num = $pl_num";

	if (!QueryDB($db, $query)) {
	   closeDB($db);
	   return;
	}

	closeDB($db);
}

# Folgende Funktion stellt eine Maske zur Erfassung eines Statusberichts
# dar. Es sind auch Navigationselemente enthalten, um bereits erfasste
# Berichte abrufen zu koennen.
#
function ManageStatus($pr_num, $pl_num, $edit=false, $lock=false) {
	global $pmlight;
	global $statusbericht;
	global $menu;
	global $rstufe;
	global $unum;
	global $dtformatshort;

	if (!$statusbericht) {
	   Error(GetMessage(-1, 354, "Der Statusbericht wurde nicht freigeschalten!"));
	   return;
	}

	if (!isset($pr_num) || $pr_num <= 0) {
	   Error(GetMessage(-1, 355, "Interner Fehler: Projektnummer wurde nicht an ManageStatus &uuml;bergeben!"));
	   return;
	}

	if (!isset($pl_num) || $pl_num <= 0) {
	   Error(GetMessage(-1, 356, "Interner Fehler: Plannummer wurde nicht an ManageStatus &uuml;bergeben!"));
	   return;
	}

	$env_lock = $_REQUEST['lock'];

	if (isset($env_lock) && ($env_lock == true || $env_lock == 1))
	   $lock = true;

	if ($edit) {
	   $ps_num = $_REQUEST['ps_num'];
	   $ps_prstat = $_REQUEST['ps_prstat'];
	   $ps_comment = stripslashes(urldecode($_REQUEST['ps_comment']));
	   $ps_status = $_REQUEST['ps_status'];
	   $ps_datum = $_REQUEST['ps_datum'];
	}

	$db = OpenDB();

	if ($lock && !$edit) {
	   $query = "select ps_num, ps_prstat, ps_comment, ps_status, ";
	   $query .= "to_char(ps_datum, 'DD.MM.YYYY') from planstatus where ";
	   $query .= "ps_prnum = $pr_num and ps_plnum = $pl_num and ";
	   $query .= "ps_status = true order by ps_datum desc";

	   if (!($resps = QueryDB($db, $query))) {
	      closeDB($db);
	      return;
	   }

	   if (numrowsDB($resps) > 0) {
	      $data = fetchDB($resps, 0);
	      $ps_num = $data[0];
	      $ps_prstat = $data[1];
	      $ps_comment = $data[2];
	      $ps_status = $data[3];
	      $ps_datum = $data[4];
	   }
	}

	$query = "select pr_name, pr_pl, mi_nname, mi_vname ";
	$query .= "from project, mitarbeiter where ";
	$query .= "mi_num = pr_pl and pr_num = $pr_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$pr_name = $data[0];
	$pr_pl = $data[1];
	$mi_nname = $data[2];
	$mi_vname = $data[3];

	if ($pr_pl != $unum && $rstufe != 1) {
	   Error(GetMessage($db, 353, "Nur der Administrator oder der Projektleiter darf den Statusbericht bearbeiten!"));
	   closeDB($db);
	   return;
	}

	$query = "select pl_status, pl_lfd from plan where pl_num = $pl_num";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$pl_status = $data[0];
	$pl_lfd = $data[1];

	switch($pl_status) {
	   case 1: $str_status = GetMessage($db, 85, "In Erstellung"); break;
	   case 2: $str_status = GetMessage($db, 86, "Freigegeben"); break;
	   case 3: $str_status = ""; break;
	   case 4: $str_status = GetMessage($db, 87, "Aktiv"); break;
	   case 5: $str_status = GetMessage($db, 88, "Inaktiv"); break;
	   case 6: $str_status = GetMessage($db, 89, "Abgeschlossen"); break;
	}

	$nav = "menu=$menu&headline=9";
	# Kopf der Maske malen
?>
<form action="plan.php" name="statb" method="post">
   <input type="hidden" name="menu" value="<? echo "$menu"; ?>">
   <input type="hidden" name="headline" value="9">
   <input type="hidden" name="pr_num" value="<? echo "$pr_num"; ?>">
   <input type="hidden" name="pl_num" value="<? echo "$pl_num"; ?>">
   <input type="hidden" name="ps_pl" value="<? echo "$pr_pl"; ?>">
   <input type="hidden" name="lock" value="<? echo "$lock"; ?>">
<?
	if (isset($ps_num) && $ps_num > 0)
	   echo "<input type=\"hidden\" name=\"ps_num\" value=\"$ps_num\">\n";

	if (isset($ps_datum))
	   echo "<input type=\"hidden\" name=\"ps_datum\" value=\"$ps_datum\">\n";

	if ($edit && !isset($ps_datum))
	   $ps_datum = date($dtformatshort);
?>
   <input type="hidden" name="func" value="SavePlanstatus">

<table class="input">
   <tr>
<?
	if ($edit || $lock) {
?>
      <th class="sel" colspan=2><? Output($db, 357, "Statusbericht vom %s", $ps_datum); ?></th>
<?
	} else {
?>
      <th class="sel" colspan=2><? Output($db, 358, "Neuen Statusbericht erfassen"); ?></th>
<?
	}
?>
      <th class="sel"><? Output($db, 359, "Alte Berichte"); ?></th>
   </tr>
   <tr>
      <td><? Output($db, 328, "Projektleiter:"); ?></td>
      <td><? echo "$mi_nname $mi_vname"; ?></td>
      <td rowspan=6 valign="top">
<?
	$query = "select ps_num, ps_plnum, ps_status, ps_comment, ps_prstat,";
	$query .= "to_char(ps_datum, 'DD.MM.YYYY') from planstatus ";
	$query .= "where ps_prnum = $pr_num ";

	if ($lock)
	   $query .= "and ps_plnum = $pl_num and ps_status = true ";

	$query .= "order by ps_lfd desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$anz = numrowsDB($result);
	$i = 0;

	if ($anz > 0)
	   echo "<table class=\"input\">\n";

	while ($i < $anz) {
	   $data = fetchDB($result, $i);
	   $xps_num = $data[0];
	   $xps_plnum = $data[1];
	   $xps_status = $data[2];
	   $xps_comment = $data[3];
	   $xps_prstat = $data[4];
	   $xps_datum = $data[5];

	   echo "<tr><td><a href=\"#\" onClick=\"javascript:MoveTo('plan.php',";
	   echo "'pr_num=$pr_num&pl_num=$xps_plnum&ps_prstat=$xps_prstat&";
	   echo "ps_num=$xps_num&ps_comment=" . urlencode($xps_comment) . "&ps_status=$xps_status&";
	   echo "ps_datum=$xps_datum&lock=$lock&func=PSEDIT&$nav')\">";
	   echo "$xps_datum</td><td><img src=\"image/";

	   switch ($xps_prstat) {
	      case 0: echo "cool.gif\" alt=\"" . GetMessage($db, 360, "Gruen"); break;
	      case 1: echo "shocked.gif\" alt=\"" . GetMessage($db, 361, "Gelb"); break;
	      case 2: echo "sad.gif\" alt=\"" . GetMessage($db, 362, "Rot"); break;
	      default: echo "huh.gif\" alt=\"" . GetMessage($db, 363, "Undefiniert");
	   }

	   echo "\" width=17 height=17></td></tr>\n";
	   $i++;
	}

	if ($anz > 0)
	   echo "</table>\n";
?>
      </td>
   </tr>
   <tr>
      <td><? Output($db, 1, "Projekt:"); ?></td>
      <td><? echo "$pr_num $pr_name"; ?></td>
   </tr>
   <tr>
      <td><? Output($db, 287, "Datum:"); ?></td>
      <td><? if ($edit || $lock) echo "$ps_datum"; else echo date($dtformatshort); ?></td>
   </tr>
   <tr>
      <td><? Output($db, 364, "Plannr./Planstatus:"); ?></td>
      <td><? echo "$pl_lfd / $str_status"; ?></td>
   </tr>
   <tr>
      <th class="sel" colspan=2><? Output($db, 38, "Statusbericht"); ?></th>
   </tr>
   <tr>
      <td><? Output($db, 365, "Planstatus:"); ?></td>
      <td><select name="ps_prstat" <? if ($lock || $pl_status > 4) echo "disabled"; ?>>
             <option class="status" value="0" <? if ($ps_prstat == 0) echo "selected"; ?>><? Output($db, 366, "Gr&uuml;n"); ?></option>
             <option class="status" value="1" <? if ($ps_prstat == 1) echo "selected"; ?>><? Output($db, 361, "Gelb"); ?></option>
             <option class="status" value="2" <? if ($ps_prstat == 2) echo "selected"; ?>><? Output($db, 362, "Rot"); ?></option>
          </select>
      </td>
   </tr>
   <tr>
      <td valign="top"><? output($db, 367, "Statusbeschreibung:"); ?></td>
      <td><textarea name="ps_comment" rows=10 cols=60 <? if ($lock || $pl_status > 4) echo "disabled"; ?>><? echo "$ps_comment"; ?></textarea></td>
   </tr>
   <tr>
      <td><? Output($db, 368, "Bericht:"); ?></td>
      <td><select name="ps_status" <? if ($lock || $pl_status > 4) echo "disabled"; ?>>
             <option value="true" <? if ($ps_status == "t" || $ps_status == "true") echo "selected"; ?>><? Output($db, 369, "G&uuml;ltig"); ?></option>
             <option value="false" <? if ($ps_status == "f" || $ps_status == "false") echo "selected"; ?>><? Output($db, 370, "Ung&uuml;ltig"); ?></option>
          </select>
      </td>
   </tr>
</table>
<?
	if ($lock) {
	   echo "</form>\n";
	   closeDB($db);
	   return;
	}
?>
<table class="indent"><tr><td>
<?
	if ($edit) {
	   ButtonLink(GetMessage($db, 371, "Neuer Bericht"), "plan.php", "pr_num=$pr_num&pl_num=$pl_num&func=PLANSTATUS&$nav");
	   echo "</td><td>";
	}

	if ($pl_status <= 4)
	   ButtonSubmit(GetMessage($db, 45, "Speichern"), "statb");

	echo "</td></tr></table></form>\n";
	closeDB($db);
}

# Folgende Funktion speichert einen zuvor erfassten Planstatus. Dabei wird
# ermittelt ob es den Plan bereits gibt oder nicht.
#
function SavePlanstatus() {
	$ps_num = $_REQUEST['ps_num'];
	$ps_prnum = $_REQUEST['pr_num'];
	$ps_plnum = $_REQUEST['pl_num'];
	$ps_pl = $_REQUEST['ps_pl'];
	$ps_status = $_REQUEST['ps_status'];
	$ps_comment = $_REQUEST['ps_comment'];
	$ps_prstat = $_REQUEST['ps_prstat'];

	if (!isset($ps_prnum) || $ps_prnum <= 0) {
	   Error("Interner Fehler: Projektnummer wurde nicht an SavePlanstatus &uuml;bergeben!");
	   return;
	}

	if (!isset($ps_plnum) || $ps_plnum <= 0) {
	   Error("Interner Fehler: Plannummer wurde nicht an SavePlanstatus &uuml;bergeben!");
	   return;
	}

	if (!isset($ps_pl) || $ps_pl <= 0) {
	   Error("Interner Fehler: Projektleiter wurde nicht an SavePlanstatus &uuml;bergeben!");
	   return;
	}

	$db = OpenDB();
	# Gibt es den Satz schon, dann machen wir nur ein Update
	if (isset($ps_num) && $ps_num > 0) {
	   $query = "select count(*) from planstatus where ps_num = $ps_num";

	   if (!($result = QueryDB($db, $query))) {
	      closeDB($db);
	      return;
	   }

	   $data = fetchDB($result, 0);

	   if ($data[0] > 0) {
	      $query = "update planstatus set ps_status = $ps_status, ";
	      $query .= "ps_comment = '$ps_comment', ps_prstat = $ps_prstat ";
	      $query .= "where ps_num = $ps_num";

	      if (!QueryDB($db, $query)) {
	         closeDB($db);
	         return;
	      }

	      closeDB($db);
	      return;
	   }
	}

	# Interne laufende Nummer ermitteln
	$query = "select ps_lfd from planstatus where ps_prnum = $ps_prnum order by ps_lfd desc";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	if (numrowsDB($result) > 0) {
	   $data = fetchDB($result, 0);
	   $ps_lfd = $data[0] + 1;
	} else
	   $ps_lfd = 0;

	# Internen Zaehler ermitteln
	$query = "select co_planstatus from counter";

	if (!($result = QueryDB($db, $query))) {
	   closeDB($db);
	   return;
	}

	$data = fetchDB($result, 0);
	$co_planstatus = $data[0] + 1;
	# Einfuegen der Daten in die Datenbank
	if (!QueryDB($db, "begin")) {
	   closeDB($db);
	   return;
	}

	$query = "insert into planstatus (ps_num, ps_pl, ps_prnum, ps_plnum,";
	$query .= "ps_status, ps_comment, ps_lfd, ps_prstat, ps_datum) ";
	$query .= "values ($co_planstatus, $ps_pl, $ps_prnum, $ps_plnum, ";
	$query .= "$ps_status, '$ps_comment', $ps_lfd, $ps_prstat, ";
	$query .= "current_timestamp)";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return;
	}

	$query = "update counter set co_planstatus = $co_planstatus";

	if (!QueryDB($db, $query)) {
	   QueryDB($db, "rollback");
	   closeDB($db);
	   return;
	}

	QueryDB($db, "commit");
	closeDB($db);
}

require_once('planlockm.inc');

# Folgende Abfrage stellt eine Maske zur Verfuegung, mit deren Hilfe
# die Stammdaten eines neuen Plans erfasst werden koennen. Es ist der Erste
# von insgesamt 3 Schritten.
# Im zweiten Schritt wird zwischen Grob und Feinplanung entschieden. Bei der
# Grobplanung werden noch keine direkten Ressourcen vergeben, wohl aber die
# Anzahl der PT und die Zeitdauer der Tasks angegeben.
# Nei der Feinplanung werden dann den Tasks Ressourcen zugeordnet. Diese
# Planung kann schlisslich in Form eines Ganttcharts ausgegeben werden.
# Bei der sp�eren IST-Erfassung werden die eingegebenen Zeiten mit den
# geplanten gegengerechnet und Abweichungen dargestellt.
#
if ($knopf == 10) {
   echo "<form name=\"temp\" action=\"plan.php\" method=\"post\">\n";
   echo "<input type=\"hidden\" name=\"pl_status\" value=\"1\">\n";
   echo "<input type=\"hidden\" name=\"headline\" value=\"19\">\n";
   echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
   echo "<input type=\"hidden\" name=\"func\" value=\"SaveNewPlan\">\n";

   echo "<table class=\"input\">\n";
   echo "<tr><td>Projekt:</td><td><select name=\"pl_prnum\">\n";

   $db = OpenDB();

   if ($rstufe == 1) {
      $query = "select pr_num, pr_name from project where pr_status = 0 ";
      $query .= "order by pr_num";
   } else {
      $query = "select pr_num, pr_name from project where ";
      $query .= "pr_pl = $unum and pr_status = 0 ";
      $query .= "order by pr_num";
   }

   $result = QueryDB($db, $query);
   $numrows = numrowsDB($result);
   $row = 0;

   while ($row < $numrows) {
      $data = fetchDB($result, $row);
      $pr_num = $data[0];
      $pr_name = $data[1];

      $query = "select count(*) from plan where pl_prnum = $pr_num and ";
      $query .= "pl_status = 6";

      if (!($respl = QueryDB($db, $query)))
	 break;

      $data = fetchDB($respl, 0);

      if ($data[0] > 0) {
	 $row++;
	 continue;
      }

      echo "<option value=\"$pr_num\">$pr_num $pr_name</option>\n";
      $row++;
   }

   echo "</select></td></tr>\n";
   echo "<tr><td>Template:</td>\n";
   echo "<td><select name=\"te_num\">\n<option value=\"0\"> -- kein Template -- </option>\n";

   $query = "select te_num, te_name from tempidx order by te_name";
   $result = QueryDB($db, $query);
   $numrows = numrowsDB($result);
   $row = 0;

   while ($row < $numrows) {
      $data = fetchDB($result, $row);
      $te_num = $data[0];
      $te_name = $data[1];
      echo "<option value=\"$te_num\">$te_name</option>\n";
      $row++;
   }

   echo "</td></tr>\n";
   echo "</table>\n";
   echo "<table class=\"indent\"><tr><td>";
   ButtonSubmit("Plan erstellen", "temp");
   echo "</td></tr></table>";
   echo "</form>\n";
}

if ($knopf == 2) {
   ShowPlan($rstufe, $menu, $unum);
//   include('start.inc');
}

if ($knopf == 11) {
   ShowPlan($rstufe, $menu, $unum);
}

if (isset($func)) {
   if ($func == "SaveNewPlan") {
      $te_num = $_REQUEST['te_num'];
      $pl_num = SaveNewPlan();

      if ($pl_num > 0 && $te_num > 0) {
	 PlanPeriode($pl_num, 0, 0);
      } else if ($pl_num > 0) {
         AddTask($pl_num, 1);
      }
   }

   if ($func == "DeletePlan") {
      if (isset($_REQUEST['yes'])) {
         DeletePlan();
	 $pl_num = $_REQUEST['pl_num'];
	 echo "<p class=\"cry\">Plan Nr.: $pl_num wurde erfolgreich gel&ouml;scht!</p>\n";
      }

      ShowPlan($rstufe, $menu, $unum);
   }

   if ($func == "DeleteTask") {
      if (isset($_REQUEST['yes'])) {
         DeleteTask();
      }

      $ta_plnum = $_REQUEST['ta_plnum'];
      PlanPeriode($ta_plnum, 0, 0);
   }

   if ($func == "GetColor") {
      GetColor();
   }

   if ($func == "SaveTask" || $func == "SaveObsoleteTask") {
      if ($func == "SaveObsoleteTask")
         $doit = true;
      else
         $doit = false;

      if (SaveTask($doit)) {
         $ta_plnum = $_REQUEST['ta_plnum'];
         PlanPeriode($ta_plnum, 0, 0);
      } else {
//         $pl_num = $_REQUEST['pl_num'];
         $ta_plnum = $_REQUEST['ta_plnum'];
	 $ta_id = $_REQUEST['ta_id'];
	 $ta_num = $_REQUEST['ta_num'];

	 if (isset($ta_num) && $ta_num > 0)
	    EditTask($ta_num);
	 else
            AddTask($ta_plnum, $ta_id);
      }
   }

   if ($func == "AddMiAdd") {
      AddMiAdd();
      $al_task = $_REQUEST['al_task'];
      AddMi($al_task);
   }

   if ($func == "AllocMa") {
      $pl_num = $_REQUEST['pl_num'];
      PlanPeriode($pl_num, 0, 0, true);
   }

   if ($func == "SaveMa") {
      $pl_num = $_REQUEST['pl_num'];
      $yes = $_REQUEST['yes'];

      if (isset($yes) && $yes == "yes")
         $yes = true;
      else
         $yes = false;

      if (!SaveMa($yes)) {
         PlanPeriode($pl_num, 0, 0, true);
      } else
         PlanPeriode($pl_num, 0, 0);
   }

   if ($func == "SaveUpMa") {
      $pl_num = $_REQUEST['pl_num'];

      if (!SaveUpMa()) {
	 $ta_num = $_REQUEST['al_task'];
	 $ressource = $_REQUEST['ressource'];
	 PlanPeriode($pl_num, $ta_num, $ressource);
      } else
         PlanPeriode($pl_num, 0, 0);
   }

   if ($func == "UpdateMa") {
      $pl_num = $_REQUEST['pl_num'];
      $ta_num = $_REQUEST['al_task'];
      $ressource = $_REQUEST['ressource'];
      PlanPeriode($pl_num, $ta_num, $ressource);
   }

   if ($func == "AskDeleteMa") {
      AskDeleteMa();
   }

   if ($func == "DeleteMa") {
      if (isset($_REQUEST['yes']))
         DeleteMa();

      $pl_num = $_REQUEST['pl_num'];
      PlanPeriode($pl_num, 0, 0);
   }

   if ($func == "EditPlStatus") {
      $pl_num = $_REQUEST['pl_num'];
      ShowPlan($rstufe, $menu, $unum, $pl_num);
      $knopf = -1;
   }

   if ($func == "UpdatePlan") {
      UpdatePlan();
      ShowPlan($rstufe, $menu, $unum);
      $knopf = -1;
   }

   if ($func == "WriteStatus") {
      if ($_REQUEST['yes'] == "yes")
         UpdatePlan(true);

      ShowPlan($rstufe, $menu, $unum);
      $knopf = -1;
   }

   if ($func == "COMMENT") {
      SavePlanComment();

      if (!isset($editplan) || $editplan <= 0) {
	 $pl_num = $_REQUEST['pl_num'];
	 PlanPeriode($pl_num, 0, 0);
      }
   }

   if ($func == "PLANSTATUS") {
      $pr_num = $_REQUEST['pr_num'];
      $pl_num = $_REQUEST['pl_num'];
      $lock = $_REQUEST['lock'];

      if ($lock)
	 ManageStatus($pr_num, $pl_num, false, true);
      else
	 ManageStatus($pr_num, $pl_num);
   }

   if ($func == "SavePlanstatus") {
      SavePlanstatus();
      $pr_num = $_REQUEST['pr_num'];
      $pl_num = $_REQUEST['pl_num'];
      ManageStatus($pr_num, $pl_num, true);
   }

   if ($func == "PSEDIT") {
      $pr_num = $_REQUEST['pr_num'];
      $pl_num = $_REQUEST['pl_num'];
      ManageStatus($pr_num, $pl_num, true);
   }

   if ($func == "LockM")
      AskLockM();

   if ($func == "LockProject") {
      LockProject();
      ShowPlan($rstufe, $menu, $unum);
   }
}

# Folgende Abfragen werden dann Aktiv, wenn der Anwender einen der
# Buttons in der ersten Spalte der durch ShowPlan() angezeigten Tabelle
# klickt.
#
if (isset($editplan) && $editplan > 0) {
   $lock = $_REQUEST['lock'];
   PlanPeriode($editplan, 0, 0);
}

if (isset($viewplan) && $viewplan > 0) {
   PlanPeriode($viewplan, 0, 0, false, true);
}

if (isset($deleteplan) && $deleteplan > 0) {
   AskDelete($deleteplan);
}

if (isset($editcopy) && $editcopy > 0) {
   if ($func == "CopyPlan") {
      $yes = $_REQUEST['yes'];
      $cancel = $_REQUEST['cancel'];

      if (isset($cancel) && $cancel == "cancel")
         $cancel = true;
      else
         $cancel = false;

      if (!isset($yes))
         $yes = false;
      else
         $yes = true;

      $doit = true;
   } else {
      $yes = false;
      $doit = false;
   }

   if (!$cancel && EditCopy($editcopy, $yes, $doit))
      Error("Plan wurde erfolgreich kopiert!");
   else if (!$cancel)
      Error("Plan konnte nicht kopiert werden!");
   else
      Error("Aktion wurde abgebrochen.");

   ShowPlan($rstufe, $menu, $unum);
}

if (isset($taskadd) && $taskadd > 0) {
   $ta_plnum = $_REQUEST['ta_plnum'];
   AddTask($ta_plnum, $taskadd);
}

if (isset($deletetask) && $deletetask > 0) {
   AskDeleteTask($deletetask);
}

if (isset($edittask) && $edittask > 0) {
   EditTask($edittask);
}

if (isset($addmi) && $addmi > 0) {
   AddMi($addmi);
}

if (isset($addmiadd)) {
   $al_task = $_REQUEST['al_task'];
   AddMi($al_task, 1);
}

if (isset($addmidel) && $addmidel > 0) {
   AddMiDel($addmidel);
   $al_task = $_REQUEST['al_task'];
   AddMi($al_task);
}

if (isset($movedown) && $movedown > 0) {
   if (MoveTask($movedown, 1)) {
      $pl_num = $_REQUEST['pl_num'];

      if (isset($pl_num) && $pl_num > 0)
         PlanPeriode($pl_num, 0, 0);
      else
         Error("Interner Fehler: Plannummer ist verloren gegangen!");
   } else
      Error ("Task konnte nicht verschoben werden!");
}

if (isset($moveup) && $moveup > 0) {
   if (MoveTask($moveup, -1)) {
      $pl_num = $_REQUEST['pl_num'];

      if (isset($pl_num) && $pl_num > 0)
         PlanPeriode($pl_num, 0, 0);
      else
         Error("Interner Fehler: Plannummer ist verloren gegangen!");
   } else
      Error ("Task konnte nicht verschoben werden!");
}

require('footer.inc');
?>
